如何使用反射从Field / Class中获取Object?

时间:2014-12-30 17:25:43

标签: java reflection

我正在使用反射将Field放在另一个类中,但是当我尝试使用f.set(...)将值设置到Field中时,我没有Object,只有Class。

我编写类似于此的代码:

Class<?> c = null;

String fieldNameAux = "id";
String classNameAux = "PedV";

try {
    c = Class.forName("beans."+classNameAux);
} catch (Exception e){}

Field f = c.getDeclaredField(fieldNameAux);
f.setAccessible(true);

f.set(**something**, ((Edit) objAux).getText();

因为我需要动态获取Class和Field,所以我不能使用这样的东西(但它有效):

Class<?> c = null;

String fieldNameAux = "id";
PedV pedV = new PedV();

c = pedV.getClass();

Field f = c.getDeclaredField(fieldNameAux);
f.setAccessible(true);

f.set(pedV, ((Edit) objAux).getText());

我怎样才能将这个f.set(pedV, ((Edit) objAux).getText();替换为动态起作用的东西?

OBS :我在数据库中收到fieldNameAuxclassNameAux

1 个答案:

答案 0 :(得分:3)

您需要创建实例。一种方法是通过c.newInstance,如果这是一个JavaBean应该是您所需要的(它试图调用该类的零参数构造函数)。否则,您需要通过getDeclaredConstructor / getDeclaredConstructors或类似的方法找到合适的构造函数,然后调用它们来获取实例。

在评论中重新提问:

  

如果我使用c.newInstance,它不会“杀死”/清除我的Field的值?

您的Field实例没有值;您从c.newInstance获得的实例。 Field只是在实例上设置数据的一种方法。

一个例子可能会有所帮助:假设我们有:

public class Foo {
    public int a;
    public int b;
}

然后我们这样做:

Class f = Class.forName("Foo");
Object inst = f.newInstance();
Field aField = f.getDeclaredField("a");
aField.setInt(inst, 42);
Field bField = f.getDeclaredField("b");
bField.setInt(inst, 67);

...现在我们通过Foo变量引用了inst个实例,a等于42,b等于67。

相关问题