Is there a preference or behavior difference between using:
if(obj.getClass().isArray()) {}
and
if(obj instanceof Object[]) {}
?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In most cases, you should use the
instanceofoperator to test whether an object is an array.Generally, you test an object’s type before downcasting to a particular type which is known at compile time. For example, perhaps you wrote some code that can work with a
Integer[]or anint[]. You’d want to guard your casts withinstanceof:At the JVM level, the
instanceofoperator translates to a specific ‘instanceof’ byte code, which is optimized in most JVM implementations.In rarer cases, you might be using reflection to traverse an object graph of unknown types. In cases like this, the
isArray()method can be helpful because you don’t know the component type at compile time; you might, for example, be implementing some sort of serialization mechanism and be able to pass each component of the array to the same serialization method, regardless of type.There are two special cases: null references and references to primitive arrays.
A null reference will cause
instanceofto resultfalse, while theisArraythrows aNullPointerException.Applied to a primitive array, the
instanceofyieldsfalseunless the component type on the right-hand operand exactly matches the component type. In contrast,isArray()will returntruefor any component type.