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

 YANLIUPING 发布于 2023-02-09 17:57

我在以下代码的代码上运行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."

相关问题:链接

1 个回答
  • 数组和一些集合在其内容仍然可变的意义上不是不可变的.

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

    试试这个:

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

    BTW,小心java命名约定.. : descriptions,不是DESCRIPTIONS

    2023-02-09 18:00 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有