Since a macro's arguments must be available at compile time, creating one
for calling a runtime defined method won't work.
Because of this we are left with *eval*, which actually compiles and then
evaluates at runtime the expression it receives as an argument.
Here's a function that receives an object, a method name (as a symbol or
string) and optional arguments; and then uses eval to find the result:
(ns calling-methods
(:require [clojure.reflect :as r]))
;-----------------------------
(defn call-method* [obj m & args]
(eval `(. ~obj ~(symbol m) ~@args)))
;-----------------------------
(def method-def (->> (r/reflect "String")
:members
(filter #(= "toString" (str (:name %))))
first))
(let [x {:a 1 :b 2}
s "hi"
upper "toUpperCase"]
(println (call-method* x (:name method-def)))
(println (call-method* "hi" (:name method-def)))
(println (call-method* "hi" upper)))
Hope it helps.
J
On Monday, February 11, 2013 5:34:00 PM UTC-3, Bauna wrote:
>
> Hey all,
> I'm a newbie that is trying to use clojure for my university grade thesis.
> In our project we have to generate a graph structure invoking some
> methods on a standard java class. This class is provided at run time, so
> the methods that need to be called must be obtained by
> reflection. I've been trying to use clojure.reflect, but I was not able to
> find a way to invoke a method on the class with the symbols retrieved from
> reflect (I know that I can use java interop and
> use standard java reflection api).
>
> Here is and example of what I want to do:
> user=> (require '[clojure.reflect :as r])
> user=> (def method-def (filter #(= "toString" (str (:name %))) (:members
> (r/reflect "aClass"))))
>
> How do I invoke "toString" using "method-definition"?
>
> Thanks and regards,
> --
> Pablo Nussembaum
>
>
>
> what is better to use java interop using java reflection API or use
> clojure.reflect to option
>
--
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
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 [email protected].
For more options, visit https://groups.google.com/groups/opt_out.