Java: Accessing private fields of superclass through reflection

You use Class.getSuperclass, Class.getDeclaredField and AccessibleObject.setAccessible as follows:

class C {
    private String privateField = "Hello World";

class SubC extends C {

class Example {
    public static void main(String[] args) throws Exception {
        SubC obj = new SubC();
        Field f = SubC.class.getSuperclass().getDeclaredField("privateField");
        String str = (String) f.get(obj);
        System.out.println(str);  // Hello World


Be the first to comment!