zoukankan      html  css  js  c++  java
  • 【java findbugs集锦】【转】May expose internal representation by incorporating reference to mutable object

    [hyddd的FindBugs分析记录][M V EI2] May expose internal representation by incorporating reference to mutable object

    [M V EI2] May expose internal representation by incorporating reference to mutable object [EI_EXPOSE_REP2]

    This code stores a reference to an externally mutable object into 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. Storing a copy of the object is better approach in many situations.

    这个问题和Inconsistent synchronization描述的问题很类似,解决方案也很类似,可以参考看看:http://www.cnblogs.com/hyddd/articles/1391098.html

    先看一段代码:

    复制代码
    public class Test  extends Thread{

        public static void main(String args[]) throws Exception{
            Test3 obj = new Test3();
            Date now = new Date();
            
            obj.setRegDate(now);    
            now.setYear(4000);  //问题所在!
            
            System.out.println(obj.getRegDate());
        }
    }

    public class Test3 {
         
        private Date regDate ;    

        public void setRegDate(Date regDate) {
            this.regDate = regDate;
        }

        public Date getRegDate() {
            return regDate;
        }    
    }
    复制代码

    这段代码的输出是:Thu Feb 15 21:47:13 CST 5900

    如果main里面不加now.setYear(4000);这句代码呢,结果是:Sun Feb 15 21:47:31 CST 2009

    从这里我们发现了,修改一个对象,可能会引起其他对象的修改,因为JAVA里,对象是引用传递的......所以这里我的建议是:setObj的时候,对象不要直接赋值(this.regDate = regDate),而是赋值传入对象的拷贝(this.regDate = (Date)regDate.clone();)。

    OK~现在我们把代码this.regDate = regDate替换成this.regDate = (Date)regDate.clone();,运行一下看看结果,噢,输出是:Sun Feb 15 21:47:31 CST 2009。

    作者:hyddd

    更多:
    http://blog.csdn.net/u014352080/article/details/48631851
     
    from:http://www.cnblogs.com/hyddd/articles/1391118.html
  • 相关阅读:
    Java代码输出到txt文件(申请专利贴源码的必备利器)
    Vmware10组建局域网
    Ubuntu14.04更换阿里云源
    Ubuntu16.04如何彻底删除Apache2
    HustOJ平台搭建
    Centos 7 联想Y430P无线网卡驱动安装 过程参考
    Windows远程CentOS桌面
    centos 7 查看系统/硬件信息及运维常用命令+联想Y430P无线网卡驱动安装
    zookeeper工作原理、安装配置、工具命令简介
    centos 7 安装五笔输入法
  • 原文地址:https://www.cnblogs.com/hager/p/6221240.html
Copyright © 2011-2022 走看看