How can Java call a private method?

In Java, one can utilize reflection to invoke private methods.

First, you need to obtain the Class object. This can be done by using the Class.forName() method with the fully qualified name of the class, or by simply using the class name followed by .class.

Next, use the getDeclaredMethod() method to obtain the specified method. You need to pass in the method name and parameter types.

Next, in order to access the method, use the setAccessible(true) method to set the accessibility of the method to true, thus allowing access to private methods.

Finally, use the invoke() method to call the method by passing in the object to which it belongs (null for static methods) and any necessary parameters.

Here is an example code:

import java.lang.reflect.Method;

public class Main {

    private void privateMethod() {
        System.out.println("调用了私有方法");
    }

    public static void main(String[] args) throws Exception {
        Class<?> clazz = Class.forName("Main");
        Method method = clazz.getDeclaredMethod("privateMethod");
        method.setAccessible(true);
        Main instance = new Main();
        method.invoke(instance);
    }
}

This way, the private method can be successfully invoked.

bannerAds