我有我的代碼如下。我看到從實例方法寫入靜態字段
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();
// ...
}
}
我在sonar anaylsis中看到以下消息。
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
除了我們正在改變doSomething方法中的靜態變量之外,我在這個實現中看到一切都沒問題。我們如何解決這個問題?
待辦事項靜態方法中的賦值? – chrylis