javaarrayscastingtostring

Calling Arrays.toString(...) to print an array from an Object variable


I'm writing a method that prints every Object that is passed to it. This works fine by calling the Object.toString() method for the object but doesn't work 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));

Solution

  • 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 to Object[]). If it is not an instance of Object[] then use reflection to create an Object[] first and then print:

    private void printAnyArray(Object aObject) {
        if (aObject.getClass().isArray()) {
            if (aObject instanceof Object[]) // can we cast to Object[]
                System.out.println(Arrays.toString((Object[]) aObject));
            else {  // we can't cast to Object[] - case of primitive arrays
                int length = Array.getLength(aObject);
                Object[] objArr = new Object[length];
                for (int i=0; i<length; i++)
                    objArr[i] =  Array.get(aObject, i);
                System.out.println(Arrays.toString(objArr));
            }
        }
    }
    

    TESTING:

    printAnyArray(new int[]{1, 4, 9, 16, 25});
    printAnyArray(new String[]{"foo", "bar", "baz"});
    

    OUTPUT:

    [1, 4, 9, 16, 25]
    [foo, bar, baz]