Search code examples
arraysreflectionclojureprimitive-types

Testing whether an object is a Java primitive array in Clojure


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 might look something like:

  (if (byte-array? object)
    (handle-byte-array object))

It's in a fairly performance-sensitive piece of code so I'd rather avoid reflection if at all possible.


Solution

  • 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