How to see if an object is an array without using reflection? How to see if an object is an array without using reflection? java java

How to see if an object is an array without using reflection?


You can use Class.isArray()

public static boolean isArray(Object obj){    return obj!=null && obj.getClass().isArray();}

This works for both object and primitive type arrays.

For toString take a look at Arrays.toString. You'll have to check the array type and call the appropriate toString method.


You can use instanceof.

JLS 15.20.2 Type Comparison Operator instanceof

 RelationalExpression:    RelationalExpression instanceof ReferenceType

At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result is false.

That means you can do something like this:

Object o = new int[] { 1,2 };System.out.println(o instanceof int[]); // prints "true"        

You'd have to check if the object is an instanceof boolean[], byte[], short[], char[], int[], long[], float[], double[], or Object[], if you want to detect all array types.

Also, an int[][] is an instanceof Object[], so depending on how you want to handle nested arrays, it can get complicated.

For the toString, java.util.Arrays has a toString(int[]) and other overloads you can use. It also has deepToString(Object[]) for nested arrays.

public String toString(Object arr) {   if (arr instanceof int[]) {      return Arrays.toString((int[]) arr);   } else //...}

It's going to be very repetitive (but even java.util.Arrays is very repetitive), but that's the way it is in Java with arrays.

See also


One can access each element of an array separately using the following code:

Object o=...;if ( o.getClass().isArray() ) {    for(int i=0; i<Array.getLength(o); i++){        System.out.println(Array.get(o, i));    }}

Notice that it is unnecessary to know what kind of underlying array it is, as this will work for any array.