通过反射,可以获取并修改构造器的权限;
定义一个懒汉模式;
//懒汉模式
class LazyMan{
private volatile static LazyMan instance = null;
private LazyMan(){ }
public static LazyMan getInstance(){
if(instance == null){
synchronized(LazyMan.class){
if(instance == null){
instance = new LazyMan();
}
}
}
return instance;
}
}
开始修改:
LazyMan instance = LazyMan.getInstance();
LazyMan instance2=null;
try {
//获取默认构造器
Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor();
//将该构造器创建权限设置为true
declaredConstructor.setAccessible(true);
//该构造器可以创建实例了
instance2 = declaredConstructor.newInstance();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
System.out.println(instance==instance2);
最终结果是:
false
所以这时就是创建了两个实例,不符合初衷,可以在构造方法中设置,避免出现这种情况;但是都是治标不治本的;最后还是要通过枚举来解决;