我在以下行上的代码上运行checkstyle时遇到此错误:
@Override
public String[] getDescriptions() {
return DESCRIPTIONS;
}
但是descriptions
IS NOT
可变。它的定义为:private static final String[] DESCRIPTIONS = new String[NUM_COLUMNS];
static {
// In a loop assign values to the array.
for (int i = 0; i < NUM_COLUMNS; ++i) {
DESCRIPTIONS[i] = "Some value";
}
}
这是完整的错误消息:
"Returning a reference to a mutable object value stored in one
of the object's fields exposes the internal representation of
the object. If instances are accessed by untrusted code, and
unchecked changes to the mutable object would compromise security
or other important properties, you will need to do something
different. Returning a new copy of the object is better approach
in many situations."
相关问题:Link
最佳答案
从它们的内容仍然可变的意义上说,数组和某些集合不是一成不变的。
Java中的不变性仅涉及对象的引用分配,而不涉及其深层内容。
试试这个:
@Override
public String[] getDescriptions() {
return Arrays.copyOf(DESCRIPTIONS, DESCRIPTIONS.length);
}
顺便说一句,请谨慎使用Java命名约定..:
descriptions
,而不是DESCRIPTIONS