我在以下代码的代码上运行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."
相关问题:链接
数组和一些集合在其内容仍然可变的意义上不是不可变的.
Java中的不变性仅涉及对象的引用赋值,而不是其深层内容.
试试这个:
@Override public String[] getDescriptions() { return Arrays.copyOf(DESCRIPTIONS, DESCRIPTIONS.length); }
BTW,小心java命名约定.. : descriptions
,不是DESCRIPTIONS