Testing whether an object is a Java primitive array in Clojure

(defn primitive-array? [o]
  (let [c (class o)]
    (and (.isArray c)
         (.. c getComponentType isPrimitive))))

For particular cases, you could use something like the following:

(defn long-array? [o]
  (let [c (class o)]
    (and (.isArray c)
         (identical? (.getComponentType c) Long/TYPE))))

To check for a byte array without the use of reflection you can do this:

(def ^:const byte-array-type (type (byte-array 0)))
(defn bytes? [x] (= (type x) byte-array-type))

Not exactly sure why, but you can even inline the byte-array-type with ^:const.


As pointed by Arthur Ulfeldt, you can use Class/forName, for example, like here:

(def byte_array_class (Class/forName "[B"))

(defn byte-array? [arr] (instance? byte_array_class arr))

If you want to avoid magic strings like "[B" when caching the classes, you can apply class to an existing array object:

(def byte_array_class (class (byte-array [])))

you can use reflection once to get the class from the name, cache this and then compare the rest to that

(def array-of-ints-type (Class/forName "[I"))
(def array-of-bytes-type (Class/forName "[B")) 
...

(= (type (into-array Integer/TYPE [1 3 4])) array-of-ints-type)
true