mardi 30 décembre 2014

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.






Aucun commentaire:

Enregistrer un commentaire