21
Feb
Accessing inner class variables via Java Reflection
Accessing inner class variables via Java Reflection:
======================================================
package practice;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class OuterClass {
class InnerClass {
int n=99;
public void myFunction() {
System.out.println("Hello from inner class method");
}
}
public static void main(String[] args) {
try {
OuterClass oc = new OuterClass();
Class<?> ic = Class.forName("practice.OuterClass$InnerClass");
Constructor<?> icc = ic.getDeclaredConstructor(OuterClass.class);
Object o = icc.newInstance(oc);
Method m = o.getClass().getDeclaredMethod("myFunction", null);
m.invoke(o, null);
Field f = o.getClass().getDeclaredField("n");
System.out.println(f.get(o));
} catch (Exception e) {
e.printStackTrace();
}
}
}
0 comments