java - 返回对存储在对象字段之一中的可变对象值的引用会暴露对象的内部表示

标签 java checkstyle mutable internals

在我的代码中为以下几行运行 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/

相关文章:

java - 使用 iText 在 PDF 文档中绘制一个矩形

java - Jackson 反序列化 JSON 对象时出现 OutOfMemoryError

java - Google Checks for Netbeans Checkstyle 插件

java - Netty 4 中的工作线程

java - Swing 星级

java - 与 Maven 父模块中的 Checkstyle 和 PMD 配置的区别

java - 如何生成 Checkstyle 报告?

java - 我怎样才能使这个对象可变

Python:引用变量(hack)

haskell - 如何在 ST monad 中创建基于向量的新数据类型