Skip to content
Advertisement

How do I pass a class to new indirectly in clojure

I have a clojure class (a namespace with a (:gen-class) clause). I then need to pass a constructed object to a java function. this works

 (java_function (my-clojure-class.))

However, if I need to refer to the class indirectly, that runs into some problems because new does not evaluate its argument. I am able to get the desired result by using

(let [my-class my-clojure-class]
     (java_function 
         (eval `(new ~(symbol (. my-class getName))))))

While this works it feels clunky. Is there a cleaner way or am I missing something ?

Advertisement

Answer

I would use the newInstance method to create a new instance from my-class that is of type java.lang.Class:

(let [my-class my-clojure-class]
  (java_function (.newInstance my-class)))

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement