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");
        f.setAccessible(true);
        String str = (String) f.get(obj);
        System.out.println(str);  // Hello World
    }
}

Comments

Be the first to comment!