Hi, I needed to call a static method on a class stored in a var
yesterday and found that it was a little bit trickier than I initially
thought. There's three way of doing it, the two first are quite
straightforward and working ;-) e.g.:
(import '(java.nio ByteBuffer FloatBuffer))
(def foo ByteBuffer)
(. foo (allocate 1024)) ; throw an exception as intended.
(defmacro allocate1 [buffer-type size]
`(. ~(eval buffer-type) (allocate ~size)))
(defn allocate2 [buffer-type size]
(eval `(. ~buffer-type (allocate ~size))))
(allocate1 foo 1024)
(allocate2 foo 1024)
Both works fine, but I'm still not sure which one is the best. The
third way is to call a static method from the class object, I've tried
something but wasn't able to get it working. It throws some weird
exception, here's the code:
(defn to-primitive [class]
(try
(let [type (.getField (identity class) "TYPE")]
(.get type Object))
(catch NoSuchFieldException _ class)))
(defmacro call-static [class name & args]
(let [arg-types (into-array
(map (comp to-primitive #(.getClass %)) args))
method (.getMethod (eval class) name arg-types)]
`(.invoke ~method ~class ~...@args)))
When calling this macro (call-static foo "allocate" 1024) it throws:
java.lang.RuntimeException: Can't embed object in code, maybe print-
dup not defined: public static java.nio.ByteBuffer
java.nio.ByteBuffer.allocate(int) (NO_SOURCE_FILE:0)
This error message is quite puzzling isn't it?
Is there any other way?
Thanks
- budu
--~--~---------~--~----~------------~-------~--~----~
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
-~----------~----~----~----~------~----~------~--~---