为 Java class 实例对象中的字段赋值

assign value to field in Java class instance object

我正在循环查找 classes 并实例化它们,但是我希望能够为它们的 public 字段赋值,请问我该怎么做?

请注意,当我遍历包时,我不知道我会找到什么,所以我不想在代码中将对象转换为 class 来访问字段,那么我可以做类似 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

谢谢!

怎么样:

try {
    myClass.getDeclaredField("a").set(obj, "test");
    myClass.getDeclaredField("b").setInt(obj, 1);
} catch (NoSuchFieldException e) {
    // Whatever needs to be done
}