[英]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.