I’m writing a method that prints every Object it get passed. This works fine by calling the Object.toString() method for the object but doesn’t works for arrays. I can find out whether it is an Array with the Object.getClass().isArray() method, but I don’t know how to cast it.
int[] a;
Integer[] b;
Object aObject = a;
Object bObject = b;
// this wouldn't work
System.out.println(Arrays.toString(aObject));
System.out.println(Arrays.toString(bObject));
If you don’t know the type you can cast the object to
Object[]and print it like this (after making sure it is indeed an array and can be cast toObject[]). If it is not an instance ofObject[]then use reflection to create anObject[]first and then print:TESTING:
OUTPUT: