在我的代码中为以下几行运行 checkstyle 时出现此错误:
@Override
public String[] getDescriptions() {
return DESCRIPTIONS;
}
但描述不是
可变的。它被定义为:
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
关于java - 返回对存储在对象字段之一中的可变对象值的引用会暴露对象的内部表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20647474/