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
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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With