Malicious code vulnerability - May expose internal representation by incorporating reference to mutable object

后端 未结 8 1630
遇见更好的自我
遇见更好的自我 2020-11-27 05:00

I have the following code in my dto class.

public void setBillDate(Date billDate) {
    this.billDate = billDate;
}

And I get an error in s

8条回答
  •  面向向阳花
    2020-11-27 05:49

    Date is mutable

    Using that setter, someone can modify the date instance from outside unintentionally

    Consider this

    class MyClass {
    
       private Date billDate;
    
    
       public void setBillDate(Date billDate) {
          this.billDate = billDate;
       }
    
    }
    

    now some one can set it

    MyClass m = new MyClass();
    
    Date dateToBeSet = new Date();
    m.setBillDate(dateToBeSet); //The actual dateToBeSet is set to m
    
    dateToBeSet.setYear(...); 
    //^^^^^^^^ Un-intentional modification to dateToBeSet, will also modify the m's billDate 
    

    To avoid this, you may want to Deep-copy before setting

    public void setBillDate(Date billDate) {
        this.billDate = new Date(billDate.getTime());
    }
    

提交回复
热议问题