Monday, July 3, 2017

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 yields false unless the right-hand operand exactly matches the component type. In contrast, isArray() will return true for any component type.

@reference_1-stackoverflow
Java array reflection: isArray vs. instanceof
Object o = new int[] { 1,2 };
System.out.println(o instanceof int[]); // prints "true"       
@reference_2_stackoverflow 
How to see if an object is an array without using reflection?

No comments:

Post a Comment