在下面的类中我声明了 myMap
public class AllMap {
public static final Map<String, String> myMap= new HashMap<>();
static {
Map.put("yy", "AA");
Map.put("xx", "BB");
}
}
我需要访问其他类中的 map 。
public class Test {
FieldMap.Map;
}
一切正常,但 Sonar 在一等舱发出警告:
Make this member "protected".
在线
public static final Map<String, String> myMap = new HashMap<>();
我应该忽略此警告还是应该将其更改为 protected ?
最佳答案
如果你需要在其他类中访问 map ,那么你应该保护它不被修改:
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class AllMap {
public static final Map<String, String> myMap;
static {
final Map<String, String> tmpMap = new HashMap<>();
tmpMap.put("yy", "AA");
tmpMap.put("xx", "BB");
myMap = Collections.unmodifiableMap(tmpMap);
}
}
您仍然可以使用它并且 SonarQube 不会将此标记为错误(因为 map 是只读的)。
阅读更多关于 Collections#unmodifiableMap(Map) 的信息.
关于java - Sonar 错误 - 让这个成员成为 "protected",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46421171/