如何从java类外部调用私有方法

如何从java类外部调用私有方法

问题描述:

我有一个 Dummy 类,它有一个名为 sayHello 的私有方法。我想从 Dummy 外面打电话给 sayHello 。我认为它应该可以反射,但我得到一个 IllegalAccessException 。任何想法???

I have a Dummy class that has a private method called sayHello. I want to call sayHello from outside Dummy. I think it should be possible with reflection but I get an IllegalAccessException. Any ideas???

使用 setAccessible(true)使用调用方法之前的方法对象。

use setAccessible(true) on your Method object before using its invoke method.

import java.lang.reflect.*;
class Dummy{
    private void foo(){
        System.out.println("hello foo()");
    }
}

class Test{
    public static void main(String[] args) throws Exception {
        Dummy d = new Dummy();
        Method m = Dummy.class.getDeclaredMethod("foo");
        //m.invoke(d);// throws java.lang.IllegalAccessException
        m.setAccessible(true);// Abracadabra 
        m.invoke(d);// now its OK
    }
}