How to invoke parent private method from child?
You can do it using reflection, but unless there is a very good reason to do so, you should first reconsider your design.
The code below prints 123, even when called from outside A.
public static void main(String[] args) throws Exception {
Method m = A.class.getDeclaredMethod("getC");
m.setAccessible(true); //bypasses the private modifier
int i = (Integer) m.invoke(new A());
System.out.println("i = " + i); //prints 123
}
public static class A {
private int getC() {
return 123;
}
}
class A{
private void a(){
System.out.println("private of A called");
}
}
class B extends A{
public void callAa(){
try {
System.out.println(Arrays.toString(getClass().getSuperclass().getMethods()));
Method m = getClass().getSuperclass().getDeclaredMethod("a", new Class<?>[]{});
m.setAccessible(true);
m.invoke(this, (Object[])null);
} catch (Exception e) {
e.printStackTrace();
}
}
}
EDIT: This is quiet an old post but adding a few nuggets of advice
Reconsider your design
Calling private method of parent, though possible through Reflection, but should not be done. Calling private methods on parent might leave the class in invalid state and may lead to unexpected behaviors.