星期一, 五月 24, 2010

java 如何确定一个对象是否数组?

Java array reflection: isArray vs. instanceof

那个方法好呢?

if(obj.getClass().isArray()) {}

and

if(obj instanceof Object[]) {}

In general, use the instanceof operator to test whether an object is an array.

At the JVM level, the instanceof operator translates to a specific "instanceof" byte code, which is highly optimized in most JVM implementations.

The reflective approach (getClass().isArray()) is compiled to two separate "invokevirtual" instructions. The more generic optimizations applied by the JVM to these may not be as fast as the hand-tuned optimizations inherent in the "instanceof" instruction.

There are two special cases: null references and references to primitive arrays.

A null reference will cause instanceof to result false, while the isArray throws a NullPointerException.

Applied to a primitive array, the instanceof results false, but the isArray returns true.

If obj is of type int[] say, then that will 
have an array Class but not be an instance of Object[].
So what do you want to do with obj. If you are going to
cast it, go with instanceof. If you are going to use

reflection, then use .getClass().isArray().

总结:
isArray的方位更加广泛。
instance Object[]不能确别int[]等数组。

所以,那个更好,要看自己的具体情况了