【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

转载于:https://www.cnblogs.com/hager/p/6221240.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值