假设我有三个类:JSONReaderConfigurationWorker. 我用JSONReader建立了Configuration的领域. 我使用WORLD从Configuration获取字段数据.
在这里,读者的例子…

public class JSONReader {
    //Read json file and it's data...
    Configuration config = Configuration.getInstance();
    config.getInstance().setURISource(reader.get("uriSource"));
}

下面是我的配置类

public class Configuration{
    private Configuration(){}
    private static Configuration instance = null;

    private final String uriSource;

    public static synchronized Configuration getInstance()
    {
        if (instance == null)
            instance = new Configuration();

        return instance;
    }

    public String setURISource(String uri){
        this.uriSource = uri;
    }

    public String getURISource(){
        return uriSource;
    }
}

这里的工人…

public class Worker {
    \\Doing some stuff, at certain point I need to get the data..
Connection connection = new Connection();    
connection.setConnection(Configuration.getInstance().getURISource()/*and other data*/);
}

我使用了singleton的方法,验证了hashcode在我的阅读器和工作器中获得Configuration的实例.hashcodes返回相同的值. 但是,getter是空的,就像变量在我的阅读器中设置后是空的一样.

有什么建议吗? idea ?

推荐答案

那是因为你打了两次getInstance().

config.getInstance().setURISource(reader.get("uriSource"));

相反,您可以直接这样做:

config.setURISource(reader.get("uriSource"));

此外,如果你想稍后设置变量,变量不能为final.

Java相关问答推荐

Selenium Java:无法访问IFRAME内部的元素

找到允许的最大底片

JPackaged应用程序启动MSI调试,然后启动System. exit()

我的scala文件失败了Scala.g4 ANTLR语法

在运行MVN测试时,为什么构建失败,并显示了java.lang.ClassNotFoundException:java.net.http.HttpResponse?

返回响应时,CamelCase命名约定不起作用

有没有办法让扩展变得多态?

当Volatile关键字真的是必要的时候?

如何在Spring Java中从数据库列中获取JSON中的具体数据

在向WebSphere中的文档添加元素时iText挂起

有谁能帮我修一下这个吗?使输出变得更加整洁

将双倍转换为百分比

有没有办法在o(log(N))中以系统的方式将数组中的小块元素复制和移动到新增长的数组中的左侧?

如何在ApacheHttpClient 5中为单个请求设置代理?

Java集合:NPE,即使没有添加空值

为什么创建Java动态代理需要接口参数

AspectJ编织外部依赖代码,重新打包jar并强制依赖用户使用它

读取ConcurrentHashMap中的可变对象

";重复键的值提示唯一约束«;livre_genre_pkey»";例外

带有提取器的JavaFXObservableList会根据侦听器的存在而改变行为