从实例方法写入静态字段

Tec*_*nch 4 java sonarqube

我的代码如下。我懂了

public MyClass{

    private static DataSource dataSource = null;

    private static DataSource getDataSource(){
        if (dataSource == null) {
            try {
                dataSource = // something.
            } catch (Exception e) {
                // some exception.
            }
        }

        return dataSource;
    }

    public List doSomething(){

        // ...

        if(dataSource == null){
            dataSource = getDataSource();
        }

        dataSource.getConnection();
        // ...

    }
}
Run Code Online (Sandbox Code Playgroud)

我在声纳分析中看到以下消息。

Dodgy - Write to static field from instance method

This instance method writes to a static field. This is tricky to get correct if multiple instances are being manipulated, and generally bad practice.
findbugs:ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD Sep12 Reliability > Architecture
Run Code Online (Sandbox Code Playgroud)

我看到在此实现中一切正常,只是我们正在doSomething方法中更改静态变量。我们该如何解决呢?

Dav*_* T. 5

不确定您的静态分析工具如何工作,但是-

尝试通过静态设置器写入您的值:

private synchronized static void setDataSource(DataSource ds) {
    dataSource = ds;
}
Run Code Online (Sandbox Code Playgroud)

这样你就可以

   if(dataSource == null){
        setDataSource(getDataSource());
   }
Run Code Online (Sandbox Code Playgroud)