I want to use Java reflection method with in Clojure function.
I think the code like (.toString {:a 1}) will parse and compile by clojure reader. So, it works by use clojure macro. But if I want to define a function to call java object method at run time , it failed. I have no idea how to invoke this kind of code with in clojure.
Here is my demo code:
(def jmethod ".toString")
(defn call-java-method [mname & body]
(let [fn1 (fn [] `(~(symbol mname) ~@body))]
(fn1)))
user=> (call-java-method jmethod 3.4M)
The result is a list (.toString 3.4M) , but I want to eval this list as a clojure function call.
As you have realized, since macros 'operate at compile-time', you essentially can't use them to call a dynamically-resolved method.
You have 2 options:
clojure.core/eval, which consists using Clojure as a runtime compiler to compile your code, then execute it.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With