I am trying to access inner class field values using reflection.
Suppose the classes are:-
public class OuterClass {
int a;
public class InnerClass {
int b;
InnerClass(int b){
this.b = b;
}
}
public void setInnerField(int val){
InnerClass a = new InnerClass(val);
}
}
And the main function has:-
OuterClass obj = new OuterClass();
obj.a = 10;
obj.setInnerField(5);
Following is what I am trying to get the inner class field value i.e. b Referred from How i can access inner class variable value using reflection in java?
Class[] classes = obj.getClass().getDeclaredClasses();
for(Class innerClass: classes){
//System.out.println(innerClass.getName());
Field[] fields = innerClass.getDeclaredFields();
for(Field field : fields){
//System.out.println(field.getName());
System.out.println(field.get(obj)); //<-----IllegalArgumentException
//Tried with below line too as suggested in above link
System.out.println(field.get(innerClass.getInterfaces())); //<-----IllegalArgumentException
}
}
Then what can be the ways to access the inner class field values at runtime?
Aucun commentaire:
Enregistrer un commentaire