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

时间:2013-01-18 11:39:55

标签: java reflection

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

2 个答案:

答案 0 :(得分:16)

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

答案 1 :(得分:2)

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

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

}