On Jan 12, 1:50 am, Konrad Hinsen <konrad.hin...@fastmail.net> wrote: > On 11 Jan 2010, at 23:09, .Bill Smith wrote: > > > Every class object has a newInstance method: > > > user=> (Class/forName "java.util.HashMap") > > java.util.HashMap > > user=> (.newInstance (Class/forName "java.util.HashMap")) > > #<HashMap {}> > > user=> > > > Is that what you are looking for? > > It seems close, but it doesn't work for me. From experimenting I have > the impression that this works only for constructors with no arguments. > > I found some stuff in the Java docs on reflection that could work, but > this is getting very complicated... I'll first see if I can do without. > > Thanks, > Konrad.
I have this lying around for situations where I need to call an arbitrary constructor: (defn construct [desc] (let [dclass (:class desc) initargs (to-array (:initargs desc)) initclasses (make-array Class (count initargs))] (doseq [i (range 0 (count initclasses))] (aset initclasses i (class (aget initargs i)))) (let [constructor (. dclass (getConstructor initclasses))] (if constructor (. constructor (newInstance initargs)) (throw (Exception. (format "no %s constructor for args: %s" (str dclass) (map str initclasses)))))))) Why the rigamarole with make-array and aset, rather than to-array or into-array? To ensure that I *always* get a Class[], even when the input list is empty (the reflection calls are finicky about that).
-- You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@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+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en