prom85 prom85 - 5 days ago 4
Java Question

Arrays - check if object is an array

Somewhere in my code I have following function:

private static Object formatArg(Object arg)
{
Object formatterArg;
if (arg instanceof Collection)
formatterArg = getFormatter().format((Collection) arg, mFormatters);
else if (arg instanceof Object[])
formatterArg = getFormatter().format((Object[]) arg, mFormatters);
else
formatterArg = getFormatter().format(arg, mFormatters, false);

return formatterArg;
}


The problem is this
arg instanceof Object[]
. The goal of this is that I want to handle
int[]
,
long[]
and any primitives arrays as well.

Question

Is it possible to find out of an
Object
is an array, no matter of which type and pass it to another function? This should work with arrays of primitive types as well as with an array of
Objects
... I can use
arg != null && arg.getClass().isArray()
to check it the
Object
is an array, but then I don't know how to pass it on (as I can't just cast and
int[]
to an
Object[]
...). Any tricks to achieve what I want?

Edit

A beautiful solution would automatically convert
int[]
to
Integer[]
,
long[]
to
Long[]
and so on. Those converted arrays would work with my
instanceof Object[]
, but this means I have to manually check for these primitive types, which I can do, but this is ugly. Any better ideas?

Answer

A quick workout to get an object array

public static void main(String[] args) {
    int[] arrInt = {23, 45, 67, 89};
    long[] arrLong = {23, 45, 67, 89};
    System.out.println(convertarrObj(arrInt));
}

static Object[] convertarrObj(Object arrObj){
    if(arrObj.getClass().isArray()) {
        Object[] objArray = new Object[Array.getLength(arrObj)];
        for(int i = 0; i < Array.getLength(arrObj) ; i++) {
            objArray[i] = Array.get(arrObj, i);
        }
        return objArray;
    }

    return null;
}

And it can be easily made sure to return an array of Integer or Long or anyother type

static Object[] convertarrObj(Object arrObj){
    Object[] objArrayObjects = null;
    if(arrObj instanceof Collection)
        return null;
    else if(arrObj.getClass().isArray()) {
        Object firstElement = Array.get(arrObj, 0);
        if (firstElement instanceof Integer) {
            objArrayObjects = new Integer[Array.getLength(arrObj)];
        } else if(firstElement instanceof Long) {
            objArrayObjects = new Long[Array.getLength(arrObj)];
        }
        for(int i = 0; i < Array.getLength(arrObj) ; i++) {
            objArrayObjects[i] = Array.get(arrObj, i);
        }
    }

    return objArrayObjects;
}

Logic behind this is auto wrapping in Java between primitive datatype and corresponding class. Determine Type of Primitive data type

Comments