Unpacking an array using reflection

I am trying to unpack the resulting array from the reflection of the fields of the objects. I set the value of the general field to Object. If it is an Array, I want to pass my shared object to an array (regardless of its type) and extract its contents

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 tried pouring the value of Object into java.util.Arrays, java.reflect.Array and Array [], but every time it does not allow me.

Is there a way I can pass my object to a shared array?

Many thanks Sam

+7
source share
2 answers

The only parent class of all arrays is Object.

To extract array values ​​as 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; } 
+10
source

Unfortunately, primitive arrays and arrays of objects do not have a common array class as an ancestor. Thus, the only option for unpacking are primitive box arrays. If you perform 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

+2
source

All Articles