Java创建不可变并且static静态的Map
rehoni / 2020-08-15
findbugs错误提示
MS_MUTABLE_COLLECTION_PKGPROTECT, Priority: Normal
XX.XX.XXX.XX is a mutable collection which should be package protected
A mutable collection instance is assigned to a final static field, thus can be changed by malicious code or by accident from another package. The field could be made package protected to avoid this vulnerability. Alternatively you may wrap this field into Collections.unmodifiableSet/List/Map/etc. to avoid this vulnerability.
很容易写的一个错误案例如下:
public class TestMap {
private static final Map<Integer,String> map = new LinkedHashMap<Integer, String>();
static {
map = new HashMap();
map.put(1, "one");
map.put(2, "two");
}
}
正确的做法 ,通过Collections.unmodifiableMap。
public class TestMap {
private static final Map<Integer,String> map ;
static {
Map<Integer,String> tempMap = new HashMap();
tempMap.put(1, "one");
tempMap.put(2, "two");
map = Collections.unmodifiableMap(tempMap);
}
}
如果现在往map里添加元素,则抛出UnsupportedOperationException异常