Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpacking an Array using reflection

I am trying to unpack an array I obtain from reflecting an objects fields. I set the value of the general field to an Object. If it is an Array I then want to cast my general Object to an array (no matter what its type) and extract its content

fields[i].setAccessible(true);
        String key = fields[i].getName();
        Object value = fields[i].get(obj);

        if (value.getClass().isArray()){
            unpackArray(value);
        }

In my unpackArray method, I have tried casting the Object Value to java.util.Arrays, java.reflect.Array and Array[] but each time it is not letting me.

Is there a way I can cast my Object to a generic array?

Many Thanks Sam

like image 271
Sam Palmer Avatar asked Nov 11 '11 14:11

Sam Palmer


2 Answers

Unfortunately primitive Arrays and Object Arrays do not have a common array class as ancestor. So the only option for unpacking is boxing primitive arrays. If you do null checks and isArray before calling this method you can remove some of the checks.

public static Object[] unpack(final Object value)
{
    if(value == null) return null;
    if(value.getClass().isArray())
    {
        if(value instanceof Object[])
        {
            return (Object[])value;
        }
        else // box primitive arrays
        {
            final Object[] boxedArray = new Object[Array.getLength(value)];
            for(int index=0;index<boxedArray.length;index++)
            {
                boxedArray[index] = Array.get(value, index); // automatic boxing
            }
            return boxedArray;
        }
    }
    else throw new IllegalArgumentException("Not an array");
}

Test: http://ideone.com/iHQKY

like image 164
Stefan Avatar answered Oct 27 '22 00:10

Stefan


The only parent class of all arrays is Object.

To extract the values of an array as an Object[] you can use.

public static Object[] unpack(Object array) {
    Object[] array2 = new Object[Array.getLength(array)];
    for(int i=0;i<array2.length;i++)
        array2[i] = Array.get(array, i);
    return array2;
}
like image 26
Peter Lawrey Avatar answered Oct 26 '22 23:10

Peter Lawrey