What\'s the best way to detect whether an object is a Java primitive array in Clojure?
The reason I need this is to do some special handling for primitive arrays, which
Props to all the other answers. Here it is as a one-liner:
(def byte-array? (partial instance? (Class/forName "[B")))
For other primitives, refer to http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getName%28%29 (or the java spec). Or just do what Gerrit suggests with (type (xyz-array 0)). Specifically you can use:
"[Z" boolean array
"[B" byte array
"[C" char array
"[D" double array
"[F" float array
"[I" integer array
"[J" long array
"[S" short array
Since performance was mentioned, here's a small benchmark result of running (time (dotimes [_ 500000] (byte-array? x))), and with byte-array-class def'd
(def byte-array? (partial instance? (Class/forName "[B")))
78.518335 msecs
(defn byte-array? [obj] (instance? byte-array-class obj))
34.879537 msecs
(defn byte-array? [obj] (= (type obj) byte-array-class))
49.68781 msecs
instance? vs type = instance? wins
partial vs defn = defn wins
but any of these approaches will likely not be a bottleneck in performance.