Check if Object is Array
In this article, we will understand different ways to check if an Object is an array in java with examples.
1. Using isArray() method
java.lang.Class
has an isArray()
method, which returns true if the object on which it is called represents an array class.
To get the class object on an object, call getClass()
method. Example,
int[] arr = new int[]{1, 2, 3}; if (arr.getClass().isArray()) { System.out.println("Object is an array"); } else { System.out.println("Object is not an array"); }
Documentation of isArray()
method states,
Determines if this Class
object represents an array class.
2. Using instanceof
Java instanceof operator checks if the object at its left is of the type of the class to its right and returns true
or false
accordingly. Example,
int[] arr = new int[]{1, 2, 3}; if (arr instanceof int[]) { System.out.println("Object is an array"); } else { System.out.println("Object is not an array"); }
In this example, we use the instanceof
operator to check if the array variable is an instance of int[]
array type.
instanceof
is more concise than isArray()
.
However, it can only be used to check for a specific array type, such as int[]
in above example.
For checking arrays of different types, we need to use all of those with instanceof
as shown below
public boolean isArray(Object obj) { return (obj instanceof boolean[] || obj instanceof byte[] || obj instanceof short[] || obj instanceof char[] || obj instanceof int[] || obj instanceof long[] || obj instanceof float[] || obj instanceof double[] || obj instanceof Object[] ); }
This method will work for objects of all types which are actually arrays, even our custom objects.
Hope the article was useful.