"Juvenn Woo" <mach...@gmail.com> writes:

> I am writing a function that'll take a java class name as an arg,
> wherein I'll make instance of the class. Several approaches did I try:
>
> (let [klass Integer] (new klass 42)) ; this raises exception "unable to 
> resolve
> symbol: klass"
>
> (let [klass Integer] (.new klass 42)) ; raises "no matching method found: new
> for class java.lang. Class"
>
> I'm running out of ideas currently. How do you deal the use case like
> this? And what's the idiomatic way to do this?

I think there's no generic predefined way to do this and you have to do
the same as what you would need to do in Java, too.  I.e., use
reflection to enumerate the given class' constructors in order to find
the one you want to call (correct number and types of its arguments).

But maybe you can use something less generic in your scenario, e.g.:

--8<---------------cut here---------------start------------->8---
(let [constructors {Integer #(Integer. %)
                    Long    #(Long. %)
                    java.awt.Dimension #(java.awt.Dimension. % %)}
      make (fn [type & args]
             (apply (constructors type) args))]
  (for [cls [Integer Long java.awt.Dimension]]
    (make cls 1)))
;;=> (1 1 #<Dimension java.awt.Dimension[width=1,height=1]>)
--8<---------------cut here---------------end--------------->8---

Bye,
Tassilo

-- 
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
--- 
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+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to