java – 如何从child调用父私有方法?
发布时间:2020-12-14 16:46:16 所属栏目:Java 来源:网络整理
导读:参见英文答案 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() }}
参见英文答案 >
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(); } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |