Java: Accessing private fields through reflection
You use Class.getDeclaredField
and AccessibleObject.setAccessible
as follows:
class C {
private String privateField = "Hello World";
}
class Example {
public static void main(String[] args) throws Exception {
C obj = new C();
Field f = C.class.getDeclaredField("privateField");
f.setAccessible(true);
String str = (String) f.get(obj);
System.out.println(str); // "Hello World"
}
}
Comments
Be the first to comment!