How do you refer to primitive Java types in Clojure?
Asked Answered
P

2

6

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 to 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?

Periphery answered 27/11, 2010 at 23:0 Comment(0)
P
12

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)>
Periphery answered 27/11, 2010 at 23:10 Comment(0)
E
0

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)))
Ent answered 25/3, 2019 at 17:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.