Java – how do I call a parent private method from child?
•
Java
See English answers > How can a derived class invoke private method of base class? 7
public class A{ private int getC(){ return 0; } } public class B extends A{ public static void main(String args[]){ B = new B(); //here I need to invoke getC() } }
Can you tell me if you can do these things through reflection in Java?
Solution
class A{
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(); } } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码