There is no subtyping relationship between arrays of primitive type, or between an array of a primitive type and array of a reference type. See JLS 4.10.3.
Therefore, the following is incorrect:
public boolean isArray(final Object obj) {
return obj instanceof Object[];
}
I use Google GWT so I am not allowed to use reflection :(
The best solution (to the isArray
array part of the question) depends on what counts as "using reflection".
If calling obj.getClass().isArray()
does not count as using reflection, then that is the best solution. Otherwise, the best way of figuring out whether an object has an array type is to use a sequence of instanceof
expressions.
public boolean isArray(final Object obj) {
return obj instanceof Object[] || obj instanceof boolean[] ||
obj instanceof byte[] || obj instanceof short[] ||
obj instanceof char[] || obj instanceof int[] ||
obj instanceof long[] || obj instanceof float[] ||
obj instanceof double[];
}
You could also try messing around with the name of the object's class as follows, but the call to obj.getClass()
is bordering on reflection.
public boolean isArray(final Object obj) {
return obj.getClass() != null &&
obj.getClass().toString().charAt(0) == '[';
}