Is there a preference or behavior difference between using:
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 yields false unless the right-hand operand exactly matches the component type. In contrast, isArray() will return true for any component type.