How can I see in Java if an Object is an array without using reflection? And how can I iterate through all items without using reflection?
I use Google GWT so I am n
You can use instanceof.
RelationalExpression: RelationalExpression instanceof ReferenceTypeAt run time, the result of the
instanceofoperator istrueif the value of the RelationalExpression is notnulland the reference could be cast to the ReferenceType without raising aClassCastException. Otherwise the result isfalse.
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.