views:

52

answers:

3

I'm using reflection to retrieve an instance field such as this:

private int[] numbers = ....

With the field object, I can check if the field contains an array and if it does, I'd like to loop over the ints in the array. So if the object that contains the above field is called "foo", then I would have something like this:

field.setAccessible(true);
Object value = field.get(foo);

The above value variable will contain my array of ints. How do I treat that object like a regular array and iterate over its values?

Edit: sorry, I missed a crucial point to my story above. I'm doing the above in a generic way so I don't know what primitive the array contains. It could be an int[] or long[] etc. So casting to int[] wouldn't work in the long[] case obviously. oops!

+1  A: 

This page has a good treatment under the "Using Arrays" section.

Simplifying (and changing variable names;-) from their array2 example class,

int valuecast[] = (int[])value;

seems to be what you're after.

Edit: the OP now clarifies that he does not know whether the primitive type in the array is int, long, or whatever. I believe the only way to deal with this is an if/else "tree" based on checks on the primitive's type (as in, Integer.TYPE or whatever) -- followed by the appropriate declaration and cast in the conditional's branch that identifies the type in question.

Alex Martelli
A: 

you can cast it to an array like this

int[] a = (int[])value;
Nikolaus Gradwohl
Sorry, I missed a crucial point in my question - I have made the correction.
digiarnie
+1  A: 

You can use the class java.lang.reflect.Array to access the length and individual elements of an array. The get method should work in a generic way, possibly wrapping primitives in their wrapper objects.

Jörn Horstmann
I can see that the get method will retrieve the value at a certain index, however, how do you get the length of the array?
digiarnie
@digiarnie, the method is a bit hidden in the javadoc between the other getters, it's `Array.getLength(Object array)` :)
Jörn Horstmann
yep that's exactly what I wanted and yes you're right, it was hidden amongst all those other getters and I just simply missed it! thanks!
digiarnie