参见英文答案 >
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() } }
你可以告诉我,如果可以通过java中的反思来做这些事情吗?
解决方法
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(); } } }