views:

97

answers:

1

I have code that uses reflection on an input object and does some processing on the data stored in the object. The input object can be anything like String or int or double etc., sometimes it can be a multi dimensional array. I know how to do it for two dimensional arrays but I would prefer something that would work for any given dimensional array. Any guidance to get this accomplished will be helpful. Thanks,

+2  A: 

Sounds like you need either 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
        }
    }
}
Michael Myers
nice answer. I worked up some similar code, but you got it first.
Yuval A
why do you need to pass in "clazz" separately? isn't it just obj.getClass()?
newacct
Ha, that's what I get for writing code in the answer box.
Michael Myers