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

dmr*_*het 13 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()
    }
}
Run Code Online (Sandbox Code Playgroud)

你能否告诉我是否有可能通过java中的反射做一些事情?

Nar*_*hai 15

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么他不能直接调用`this.getC()`? (2认同)

ass*_*ias 9

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

下面的代码打印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;
    }
}
Run Code Online (Sandbox Code Playgroud)