[英]Cast field via reflection to array type in Java
I want to get private field of array of TextView via reflection, but I need to cast this field back to the array. 我想通过反射获取TextView数组的私有字段,但是我需要将此字段强制转换回数组。
Field f= FieldUtils.getDeclaredField(ContentAdapter.ViewHolder.class, "button_massive", true);
Explicit cast like this TextView[] f1 = ((TextView[]) f)
don't work. 这样的显式转换
TextView[] f1 = ((TextView[]) f)
不起作用。
Thank you in advance! 先感谢您!
You're directly typecasting the Field
type to array. 您直接将
Field
类型转换为数组。 That certainly won't work. 那当然是行不通的。 What you want is to get the value of
f
, using Field#get()
method. 您想要的是使用
Field#get()
方法Field#get()
f
的值。 And then typecast that result to Object[]
. 然后将结果转换为
Object[]
。
Field f= FieldUtils.getDeclaredField(ContentAdapter.ViewHolder.class, "button_massive", true);
Object[] result = (Object[]) f.get(obj);
If you really want TextView
type array, then you've to create the array using and populate it from above Object[]
: 如果您确实需要
TextView
类型的数组,则必须使用创建数组并从Object[]
上方填充它:
TextView[] f1 = new TextView[result.length];
// Iterate over the `Object` array, and populate `f1` array.
I haven't tested this out, but it should be working. 我还没有测试过,但是应该可以。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.