测试对象是否是Clojure中的一个Java基本数组

测试对象是否是Clojure中的一个Java基本数组

问题描述:

什么是检测一个对象是否是Clojure中的一个Java基本类型数组的最佳方式?

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))

这是在code的相当性能敏感的一块,所以我宁愿避免反光,如果在所有可能的。

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

您可以使用反射一次,从名字,这个缓存,然后拿到类
其余比较了

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