1

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@TJCrowder Oh thanks, now I've got what you meant... it will help a lot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.