Collection、Date、Map、Calendar 等)字段的返回值或从方法形参到数组或可变类型字段的赋值。
由于这种类型是可变的,此结构可能会导致来自所属类之外的对象状态发生意外修改。 尽管出于性能原因,此结构可能很有用,但它本质上很容易出现错误。
报告了以下可变类型:
java.util.Datejava.util.Calendarjava.util.Collectionjava.util.Mapcom.google.common.collect.Multimapcom.google.common.collect.Table该快速修复会为数组添加对字段的 .clone() 方法的调用,或使用不可修改的集合包装器。
示例:
import java.util.*;
class Log {
private String[] messages = {"one", "two", "three"};
private Map<String, String> map = new HashMap<>();
String[] getMessages() {
return messages; // 警告:返回 String[] 字段 'messages'
}
Map<String, String> mapping() {
return map; // 警告:返回 Map<String, String> 字段 'map'
}
}
在应用快速修复后:
import java.util.*;
class Log {
String[] messages = {"one", "two", "three"};
private Map<String, String> map = new HashMap<>();
String[] getMessages() {
return messages.clone();
}
Map<String, String> mapping() {
return Collections.unmodifiableMap(map);
}
}
使用忽略 private 方法中的赋值和返回值选项可忽略 private方法中的赋值和返回值。