I'd like to use reflection to get a method of a Java object from Clojure. One of the argument types is a Java primitive and I don't know how to refer 开发者_如何学JAVAto them from Clojure.
For example, say I wanted to get String.valueOf(boolean)
. My nearest guess would be to do
(.getDeclaredMethod String "valueOf" (into-array [Boolean]))
but this fails because Boolean
is not the primitive type itself, but the boxed version. I've tried boolean
, but that refers to a built-in Clojure function, and bool
is undefined.
How do I refer to a primitive Java type in Clojure?
You can refer to the primitive types through the TYPE
property of their boxed equivalent. For example:
user=> (.getDeclaredMethod String "valueOf" (into-array [Boolean/TYPE]))
#<Method public static java.lang.String java.lang.String.valueOf(boolean)>
On a related note, if you want to find the Java Class object for an array of primitives, you can use this trick from the tupelo.types
namespace:
; An instance of the java.lang.Class<XXXX[]> (e.g. java.lang.Class<Byte[]>).
(def ^:private class-boolean-array (.getClass (boolean-array 0)))
(def ^:private class-byte-array (.getClass (byte-array 0)))
(def ^:private class-char-array (.getClass (char-array 0)))
(def ^:private class-double-array (.getClass (double-array 0)))
(def ^:private class-float-array (.getClass (float-array 0)))
(def ^:private class-int-array (.getClass (int-array 0)))
(def ^:private class-long-array (.getClass (long-array 0)))
(def ^:private class-object-array (.getClass (object-array 0)))
(def ^:private class-short-array (.getClass (short-array 0)))
This is used for type testing such as:
(defn boolean-array?
"Returns true is the arg is a boolean array, else false."
[arg]
(= class-boolean-array (.getClass arg)))
精彩评论