How to call a private method in Java?

In Java, private methods can only be called within their own class. If you want to call a private method in another class, you can achieve this using reflection.

Below is an example code demonstrating how to use reflection to invoke a private method.

import java.lang.reflect.Method;

public class PrivateMethodExample {

    private void privateMethod() {
        System.out.println("This is a private method.");
    }

    public static void main(String[] args) throws Exception {
        PrivateMethodExample example = new PrivateMethodExample();

        // 获取私有方法
        Method method = PrivateMethodExample.class.getDeclaredMethod("privateMethod");

        // 设置私有方法可以被访问
        method.setAccessible(true);

        // 调用私有方法
        method.invoke(example);
    }
}

In the code above, we first create a PrivateMethodExample class containing a private method privateMethod. We then use reflection in the main method to access the private method and call it. It is important to note that we need to set the private method to be accessible by using method.setAccessible(true).

Leave a Reply 0

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


广告
Closing in 10 seconds
bannerAds