如何从孩子调用父私有方法?

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中的reflection做一些事情?

 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(); } } } 

您可以使用reflection来完成,但除非有充分的理由这样做,否则您应该首先重新考虑您的设计。

下面的代码打印123,即使从外面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; } } 

你应该声明getc protected。 这正是它的用途。

至于反思:是的,这是可能的。 您必须在方法对象上调用setAccessible。 这是糟糕的风格… 😉

getDeclaredMethod只返回当前类中的私有方法而不返回inheritance的方法。 要实现它,您需要通过getSuperclass方法导航inheritance图。 这是一个执行它的代码片段

  private Method getPrivateMethod(Object currentObject) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Class currentClass = currentObject.getClass(); Method method = null; while (currentClass != null && method == null) { try { method = currentClass.getDeclaredMethod("getC"); } catch (NoSuchMethodException nsme) { // method not present - try super class currentClass = currentClass.getSuperclass(); } } if (method != null) { method.setAccessible(true); return method; } else { throw new NoSuchMethodException(); } 

}

你可以尝试这样使用reflection:

  Method getCMethod = A.class.getDeclaredMethod("getC"); getCMethod.setAccessible(true); getCMethod.invoke(new A());