How to call a private method from outside a java class

Hamed Rajabi picture Hamed Rajabi · Jul 1, 2012 · Viewed 61.9k times · Source

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???

Answer

Pshemo picture Pshemo · Jul 1, 2012

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
    }
}