代码改变世界

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

2009-02-15 22:11  hyddd  阅读(10340)  评论(0编辑  收藏  举报

[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。