Collections.unmodifiableMap()用法

Collections.unmodifiableMap()用法

中间层有时会初始化一些final的静态的Map供给一些字段做映射,一般如下:

public final static Map<String, String> TYPE = new HashMap();
static {
    TYPE.put(MYSQL,"mysql");
    TYPE.put(SQLSERVER,"sqlserver");
}

但是代码检查时会报错:

A mutable collection instance is assigned to a final static field, thus can be changed by malicious code or by accident from another package. Consider wrapping this field into Collections.unmodifiableSet/List/Map/etc.

就是说声明了final static,这个map还是可以修改,所以这里需要一个不可更改的map,Collections.unmodifiableMap()方法会返回一个“只读”的map,当你调用此map的put方法时会抛错。用法如下:

public static final Map<String,String> TYPE ;
static {
    Map<String,String> tempMap  = new HashMap();
    tempMap.put(MYSQL,"mysql");
    tempMap.put(SQLSERVER,"sqlserver");
    TYPE = Collections.unmodifiableMap(tempMap);
}

如果向转化后的map中put数据会报throw new UnsupportedOperationException()错误。

你可能感兴趣的:(Java)