返回对存储在对象的一个 字段中的可变对象值的引用会公开对象的内部表示

问题描述 投票:6回答:2

我在以下代码的代码上运行checkstyle时遇到此错误:

@Override
public String[] getDescriptions() {
    return 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 checkstyle mutable
2个回答
6
投票

数组和一些集合在其内容仍然可变的意义上不是不可变的。

Java中的不变性仅涉及对象的引用赋值,而不是其深层内容。

试试这个:

@Override
public String[] getDescriptions() {
    return Arrays.copyOf(DESCRIPTIONS, DESCRIPTIONS.length);
}

BTW,警告java命名约定..:descriptions,而不是DESCRIPTIONS


1
投票

引用变量是final,因此您无法将另一个数组分配给DESCRIPTIONS。但是,对象本身是可变的(数组总是可变的),final或不。如果返回引用,则会失去对变量内容的控制,从而违反封装。

您需要返回数组的副本,或者根本不返回数组,提供一种方法来获取数组的特定元素,如果这足够好的话。

© www.soinside.com 2019 - 2024. All rights reserved.