【FindBugs】Storing reference to mutable object-1
报错
FindBugs: May expose internal representation by incorporating reference to mutable object 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 u nchecked 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
FindBugs:可以通过合并对可变对象的引用来公开内部表示这段代码将对外部可变对象的引用存储到对象的内部表示中。如果实例是由不受信任的代码访问的,并且对可变对象所做的未检查的更改会损害安全性或其他重要属性,那么您需要做一些不同的操作。在许多情况下,存储对象的副本是更好的方法
public Date getDeadline() {
return deadline;
}
public AlarmIndependentTempData setDeadline(Date deadline) {
this.deadline = deadline;
return this;
}
解释
说实话这个中文我也看的不大明白,只知道它的大概意思是如果这个对象由不信任的代码访问,就可能会被修改,建议我们存储对象的副本。
这就涉及引用对象了,如果说我们直接把该对象中的属性deadline直接赋值或者返回,就是将在其他地方创建的对象原封不动地放入到这个属性deadline,然后再在其他地方修改那个创建出来的对象,这里的属性deadline也会修改,如果其他地方获得这个属性deadline,就有修改这个属性的机会,这就不能达到我们封装对象的目的了
解决方案
public Date getDeadline() {
//这里再作个非空判断
return (Date) deadline.clone();
}
public AlarmIndependentTempData setDeadline(Date deadline) {
//这里再作个非空判断
this.deadline = (Date) deadline.clone();
return this;
}

浙公网安备 33010602011771号