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

4

5 回答 5

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

编辑:这是一个安静的旧帖子,但添加了一些建议

重新考虑你的设计

调用父级的私有方法,虽然可以通过反射,但不应该这样做。在父类上调用私有方法可能会使类处于无效状态并可能导致意外行为。

于 2013-01-18T11:55:58.467 回答
10

您可以使用反射来做到这一点,但除非有很好的理由这样做,否则您应该首先重新考虑您的设计。

下面的代码打印 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;
    }
}
于 2013-01-18T11:45:31.520 回答
4

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

至于反思:是的,这是可能的。不过,您必须在方法对象上调用 setAccessible 。而且风格很糟糕... ;-)

于 2013-01-18T11:46:16.053 回答
3

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

}

于 2015-08-28T15:33:36.763 回答
0

你可以尝试使用反射:

    Method getCMethod = A.class.getDeclaredMethod("getC");
    getCMethod.setAccessible(true);
    getCMethod.invoke(new A());
于 2013-01-18T11:45:40.143 回答