我正在迭代查找类并实例化它们的包,但是我希望能够将值分配给它们的公共字段,我该怎么办呢?
请注意,因为我正在迭代包,我不知道我会找到什么,所以我不想在代码中强制对象类来访问字段,所以我可以做一些像obj这样的事情.getDeclaredFields()?并以某种方式使用它?
public class Test {
public String a;
public int b;
}
Class myClass = Class.forName("Test");
Object obj = myClass.getInstance(); //This is what I have so far
obj.a = "test";
obj.b = 1; // I need something like this
Test t = (Test)obj; // I dont want to have to do this as the next step
谢谢!
答案 0 :(得分:0)
怎么样:
try {
myClass.getDeclaredField("a").set(obj, "test");
myClass.getDeclaredField("b").setInt(obj, 1);
} catch (NoSuchFieldException e) {
// Whatever needs to be done
}