Reflective and multidimensional arrays

I have a code that uses reflection on the input object and does some processing of the data stored in the object. The input object can be anything, for example, String or int or double, etc., Sometimes it can be a multidimensional array. I know how to do this for two-dimensional arrays, but I would prefer something that will work for any given array of sizes. Any recommendations to achieve this would be helpful. Thanks,

+4
source share
1 answer

It looks like you need a recursion or a loop, or both.

void getStuffFromArray(Object obj) { // assuming we already know obj.getClass().isArray() == true Class<?> componentType = obj.getClass().getComponentType(); int size = Array.getLength(obj); for (int i = 0; i < size; i++) { Object value = Array.get(obj, i); if (value.getClass().isArray()) { getStuffFromArray(value); } else { // not an array; process it } } } 
+6
source

All Articles