Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using reflection to retrieve an array of primitives of an unknown type

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!

like image 520
digiarnie Avatar asked Aug 04 '10 04:08

digiarnie


2 Answers

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.

like image 93
Jörn Horstmann Avatar answered Nov 07 '22 07:11

Jörn Horstmann


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.

like image 28
Alex Martelli Avatar answered Nov 07 '22 05:11

Alex Martelli