简体   繁体   English

使用反射来检索未知类型的基元数组

[英]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. 使用field对象,我可以检查字段是否包含数组,如果有,我想循环遍历数组中的int。 So if the object that contains the above field is called "foo", then I would have something like this: 因此,如果包含上述字段的对象被称为“foo”,那么我会有这样的事情:

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

The above value variable will contain my array of ints. 上面的值变量将包含我的int数组。 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. 它可能是一个int []或long []等。所以强制转换为int []在long []情况下是行不通的。 oops! 哎呀!

You can use the class java.lang.reflect.Array to access the length and individual elements of an array. 您可以使用java.lang.reflect.Array类来访问数组的长度和单个元素。 The get method should work in a generic way, possibly wrapping primitives in their wrapper objects. get方法应该以通用方式工作,可能在其包装器对象中包装原语。

This page has a good treatment under the "Using Arrays" section. 此页面在“使用阵列”部分下有一个很好的处理。

Simplifying (and changing variable names;-) from their array2 example class, array2示例类中简化(和更改变量名称;-),

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. 编辑 :OP现在澄清他不知道数组中的原始类型是intlong还是其他。 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. 我认为处理这个问题的唯一方法是基于对原语类型的检查(如, Integer.TYPE或其他)的if/else “树” - 接着是相应的声明并在条件的分支中强制转换,以识别输入有问题。

Mentioned in Oracles Tutorial this is easily achievable with array.getClass().getComponentType() . 在Oracles Tutorial中提到过,使用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;
}

你可以把它投射到像这样的数组

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM