利用java反射机制调用类的私有方法
1.将getInstance()方法设置为private
public class Singleton {
private static Singleton instance = null;
private static synchronized Singleton getInstance() {
System.out.println("调用 私有的单例!");
if (instance==null)
instance=new Singleton();
return instance;
}
}
2.使用反射机制调用getInstance()方法
import java.lang.reflect.Method;
public class test {
public static void main(String[] args) {
Class cl = null;
try{
cl=Singleton.class;
Method m1 =cl.getDeclaredMethod("getInstance");
m1.setAccessible(true);// 调用private方法的关键一句话
m1.invoke(cl);
}catch(Exception e){
e.printStackTrace();
}
本文介绍如何通过Java反射机制来调用一个类的私有静态方法getInstance()。首先,将getInstance()方法设为私有,然后利用反射机制获取该方法并设置可访问性,最终实现对私有方法的调用。
361

被折叠的 条评论
为什么被折叠?



