What will be the output of the following code?

package question;

import java.lang.reflect.Method;


class Test {

    public void methodPublic() {
        System.out.println("Test.methodPublic");
    }

    protected void methodProtected() {
        System.out.println("Test.methodProtected");
    }

    private void methodPrivate() {
        System.out.println("Test.methodPrivate");
    }
}

public class PrivateTest {

    public static void main(String[] args) throws Exception {
        Test test = new Test();
        callMethods(test, "methodPublic");
        callMethods(test, "methodProtected");
        callMethods(test, "methodPrivate");
    }


    static void callMethods(Object a, String methodName) throws Exception {
        Method m = a.getClass().getDeclaredMethod(methodName);
        m.setAccessible(true);
        m.invoke(a);
    }

}

Explanation
Reflection allows invocation of all methods, including the private ones. The invocation is being made possible by calling setAccessible(true) on a Method object.

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback