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 genera
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;
}