Collection, Date, Map, Calendar, etc.
由于这种类型是可变的,此结构可能会导致来自所属类之外的对象状态发生意外修改。 尽管出于性能原因,此结构可能很有用,但它本质上很容易出现错误。
报告了以下可变类型:
java.util.Datejava.util.Calendarjava.util.Collectionjava.util.Mapcom.google.common.collect.Multimapcom.google.common.collect.TableThe quick-fix adds a call to the field's .clone() method for arrays or uses an unmodifiable collection wrapper.
示例:
import java.util.*;
class Log {
private String[] messages = {"one", "two", "three"};
private Map<String, String> map = new HashMap<>();
String[] getMessages() {
return messages; // warning: Return of String[] field 'messages'
}
Map<String, String> mapping() {
return map; // warning: Return of Map<String, String> field '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方法中的赋值和返回值。