How to invoke parent private method from child? [duplicate]

爱⌒轻易说出口 提交于 2020-01-10 13:32:47

问题


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 please tell me if it is possible to do sush thing via reflection in java?


回答1:


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



回答2:


You can do it using reflection, but unless there is a very good reason to do so, you should first reconsider your design.

The code below prints 123, even when called from outside 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;
    }
}



回答3:


You should declare getc protected. That's exactly what it's for.

As for reflection: Yes, it is possible. You'd have to call setAccessible on the method object though. And it's bad style... ;-)




回答4:


getDeclaredMethod will only return the private methods in the current class not the inherited methods. To achieve it you need to navigate the inheritance graph via the getSuperclass method. Here is a code snippet that does it

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

}




回答5:


you can try like this using reflection:

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


来源:https://stackoverflow.com/questions/14398157/how-to-invoke-parent-private-method-from-child

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!