Executing private methods in Java

Normally, private methods in a class are not visible to other classes and cannot be executed. However, through reflection, which enables dynamic retrieval of classes and data structures by name, you can still access and execute private methods in another class.

Consider the following class, which defines a public method called getValue1 and a private method called getValue2:

public class OtherClass {

    public String getValue1(int number) {
        return "public value " + number;
    }

    private String getValue2(int number) {
        return "private value " + number;
    }
}

Normally this is how you would call the public method getValue1:

OtherClass myClass1 = new OtherClass();
System.out.println(myClass1.getValue1(123));

If your code had contained the following line:

System.out.println(myClass1.getValue2(456));

it wouldn’t have compiled due to the following error:
error: getValue2() has private access in OtherClass

The example below illustrates how you can use reflection to call the private method getValue2 in OtherClass:

import java.lang.reflect.Method;

public class MainClass {

    public static void main(String[] args)
        throws Throwable
    {
        OtherClass myClass1 = new OtherClass();

        System.out.println(myClass1.getValue1(123));

        // MainClass.java: error: getValue2() has private access in OtherClass
        //System.out.println(myClass1.getValue2(456));

        String val = (String) callMethod(
            myClass1, "getValue2", new Object[] {456});
        System.out.println(val);
    }

    public static Object callMethod(Object object,
        String methodName, Object[] args)
        throws Throwable
    {
        Class<?> clazz = object.getClass();
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            if (methodName.equals(method.getName())) {
                method.setAccessible(true);
                return method.invoke(object, args);
            }
        }
        return null;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*