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();
}