开发者

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 doe开发者_如何学Cs, 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!


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.


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.


you can cast it to an array like this

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


Mentioned in Oracles Tutorial this is easily achievable with array.getClass().getComponentType(). This returns the class of the instances in the array.

Afterwards you can check it against the primitive class located inside each wrapper object. For example:

if (array.getClass().getComponentType().equals(Boolean.TYPE)) {
    boolean[] booleanArray =  (boolean[]) array;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜