Constructing java classes from a string containing the class name

63 views
Skip to first unread message

Dave Snowdon

unread,
Mar 17, 2013, 4:10:00 AM3/17/13
to clo...@googlegroups.com
I need the ability to create one of a number of java classes which have constructors taking a known list of parameters. There are a large enough number of classes that having a set of conditions testing for each class name would be unmanageable. The classes are from a third-party jar file so I cannot modify them either.

The trouble is that new is special form and does not evaluate it's first parameter so if I write an expression like
(new (Class/forName klassname)  param1 param2) it fails because (Class/forName klassname)  is treated as the class name rather than being evaluated first.

The closest I've got so far is to write the following macro

(defmacro make-proxy
  "Build proxy class from name and map"
  [klassname params] (list 'new (Class/forName klassname) '(:hostname params) '(:port params)))

This gets me some of the way, I can now write
(make-proxy "com.example.foo" {:hostname "127.0.0.1 :port 9559})
but it only works for constant strings since the first parameter is evaluated when the macro is expanded.

Can anyone suggest a solution?

thanks

Dave

dennis zhuang

unread,
Mar 17, 2013, 4:16:42 AM3/17/13
to clo...@googlegroups.com
You can get the constructor and instance it:

(-> klassname (Class/forName) (.getDeclaredConstructors String int) (.newInstance host port))

2013/3/17 Dave Snowdon <dave.s...@gmail.com>
--
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clo...@googlegroups.com
Note that posts from new members are moderated - please be patient with your first post.
To unsubscribe from this group, send email to
clojure+u...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
---
You received this message because you are subscribed to the Google Groups "Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email to clojure+u...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 



--
庄晓丹
Email:        killm...@gmail.com xzh...@avos.com
Site:           http://fnil.net
Twitter:      @killme2008


dennis zhuang

unread,
Mar 17, 2013, 4:18:27 AM3/17/13
to clo...@googlegroups.com
Sorry,it's getDeclaredConstructor:

(-> klassname (Class/forName) (. getDeclaredConstructor String int) (.newInstance host port))


2013/3/17 dennis zhuang <killm...@gmail.com>

Dave Snowdon

unread,
Mar 17, 2013, 8:22:35 AM3/17/13
to clo...@googlegroups.com
Great! Many thanks.
Dave
Reply all
Reply to author
Forward
0 new messages