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();
}
本文介绍了一种实现单例模式的方法,并通过将getInstance()方法设为私有来限制其访问。此外,还展示了如何利用反射机制绕过这一限制,以调用私有的getInstance()方法。
359

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



