栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

未将类中的成员属性变为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);
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/531598.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号