How to use Java classes dynamically in clojure?

How to use Java classes stored in variables in clojure?

How do I fix the following code?

(def a java.lang.String)
(new a "1"); CompilerException java.lang.IllegalArgumentException: Unable to resolve classname: a

Why does this work?

(def a str)
(a "1")

Solution

The most elegant solution is to write a construct that is the same as new but can dynamically receive classes:

(defn construct [klass & args]
    (clojure.lang.Reflector/invokeConstructor klass (into-array Object args)))
 (def a HashSet)
 (construct HashSet '(1 2 3)); It works!!!

This solution overcomes the limitations of @ mikera's answer (see comments)

Special thanks @ Micha ł Marczyk, let me know that invokeconstructor answers another question: clojure: how to create a record inside a function

Another option is to store the call as an anonymous function in the constructor In our case

(def a #(String. %1))
(a "111"); "111"
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>