Search code examples
javareflectioncallprivate

How to use reflection to call a private method from outside a java class without getting 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???


Solution

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

    If someone is interested in invoking methods with parameters see How do I invoke a Java method when given the method name as a string?, specifically answer like https://stackoverflow.com/a/30671481.

    Just don't forget to add setAccessible(true) while invoking private methods.