未将类中的成员属性变为static引发的错误

未将类中的成员属性变为static引发的错误,第1张

未将类中的成员属性变为static引发的错误

 

以下代码是单例模式的代码
a变量要为静态的,表示每个类独一份,不然是每个对象独一份,即使在空参构造方法中将a变为true,a仅仅在当前对象中为true,再new一个新的任然为false,会导致依然能成功创建两个对象

这是一个低级的错误,最后在if语句里面输出a修改后的状态才恍然大悟
public class LazyMan {
    private boolean a =false;
    private LazyMan(){
            synchronized (LazyMan.class){
                if(a==false){
                    a=true;
                }else {
                    throw new RuntimeException("不要试图使用反射破坏异常");
                }

            }
        //System.out.println(Thread.currentThread().getName()+" ok ");
    }
    private static LazyMan lazyMan;

    public static LazyMan Instance(){
        if(lazyMan==null){
            synchronized (LazyMan.class){
                if(lazyMan==null){
                    lazyMan=new LazyMan();
                }
            }
        }
        return lazyMan;
    }

    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        LazyMan instance = LazyMan.Instance();

        Constructor declaredConstructor = LazyMan.class.getDeclaredConstructor(null);
        declaredConstructor.setAccessible(true);
        LazyMan lazyMan = declaredConstructor.newInstance();
        System.out.println(instance);
        System.out.println(lazyMan);
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5523687.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-13
下一篇 2022-12-13

发表评论

登录后才能评论

评论列表(0条)

保存