Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 213
mikera Avatar asked Feb 01 '12 03:02

mikera


1 Answers

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
like image 53
Arthur Ulfeldt Avatar answered Nov 16 '22 03:11

Arthur Ulfeldt