• 【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
  • 相关阅读:
    239. [LeetCode ]Sliding Window Maximum
    152.[LeetCode] Maximum Product Subarray
    53. [LeetCode] Maximum Subarray
    90 [LeetCode] Subsets2
    78[LeetCode] Subsets
    练习7.52
    练习7.47、7.48、7.49、7.51
    关于类类型的隐式类型转换
    练习7.44、7.45、7.46
    练习7.36、7.37、7.39、7.40
  • 原文地址:https://www.cnblogs.com/hager/p/6221240.html
Copyright © 2020-2023  润新知