[英]Value of a field of Java object dynamically (by reflection)
我在这样的类中得到各个字段的名称:
Field[] f = MyClass.class.getDeclaredFields();
Sring str = f[0].toString();
MyClass cl = new MyClass();
现在我想动态地从对象cl
访问(公共)字段str
。 我怎么做?
像这样使用Field.get
方法(对于第0个字段):
Object x = f[0].get(cl);
要弄清楚str
字段有哪些索引,你可以做
int strIndex = 0;
while (!f[strIndex].getName().equals("str"))
strIndex++;
这是一个完整的例子来说明它:
import java.lang.reflect.Field;
class MyClass {
String f1;
String str;
String f2;
}
class Test {
public static void main(String[] args) throws Exception {
Field[] f = MyClass.class.getDeclaredFields();
MyClass cl = new MyClass();
cl.str = "hello world";
int strIndex = 0;
while (!f[strIndex].getName().equals("str"))
strIndex++;
System.out.println(f[strIndex].get(cl));
}
}
输出:
hello world
Field f = Myclass.class.GetField("Str");
MyClass cl = new MyClass();
cl.Str = "Something";
String value = (String)f.get(cl); //value == "Something"
应该是这样的:
Field[] f = MyClass.class.getDeclaredFields();
MyClass targetObject = new MyClass();
...
Object fieldValue = f[interestingIndex].get(cl);
注意例外情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.