João Rocha
João Rocha

Reputation: 135

How can I get the Object from a Field/Class using reflection?

I'm using reflection to get the Field at another Class, but when I try to use the f.set(...) to set a value into the Field, I dont have a Object, only the Class.

I code something similar to this:

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();

As I need get the Class and the Field dynamically I can't use something like this (but it works):

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());

How could I substitute this f.set(pedV, ((Edit) objAux).getText(); for something that works dynamically?

OBS: I'm getting fieldNameAux and classNameAux in a database.

Upvotes: 1

Views: 71

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075377

You need to create an instance. One way is via c.newInstance, which if this is a JavaBean should be all you need (it attempts to invoke the zero-args constructor for the class). Otherwise, you need to find an appropriate constructor via getDeclaredConstructor/getDeclaredConstructors or similar and then invoke them to get an instance.

Re your question in a comment:

If i use c.newInstance it won't "kill"/clear my Field's values?

Your Field instance doesn't have values; the instance you get from c.newInstance does. Field is just a means of setting the data on the instance.

An example may help: Suppose we have:

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

Then we do this:

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);

...now we have a Foo instance we're referring to via our inst variable, which has a equal to 42 and b equal to 67.

Upvotes: 3

Related Questions