Reputation: 832
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.
Upvotes: 3
Views: 331
Reputation: 6061
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.Upvotes: 1