Findbugs issues with mutability of Date object in Java

若如初见. 提交于 2019-12-19 05:20:39

问题


This is more of a follow-up to questions 1 & 2.

As told in the questions the below code

public Date getSomeDate() {
   return someDate;
}

will give you the findbug error issue.

The suggested solution was to duplicate the Date object in both getters and setters like

public Date getSomeDate() {
  return new Date(someDate.getTime());
} 

Is this a good approach or are there any alternative ways to this?

Is there any Immutable Date library available in java that can overcome this issue?


回答1:


JodaTime has immutable dates.

Sure, it's okay to use a Date constructor in a getter, why wouldn't it be?

That said, just because FindBugs pegs mutable state as a potential error, it doesn't mean it's intrinsically worth caring about–it depends on how the class is being used. Immutability eliminates one type of bug, which you may or may not need to care a lot about.




回答2:


Attention Folks...

besides adapting both the getter and the setter you need to take care about null values:

public Date getSomeDate() {
  if (this.someDate == null) {
    return null;
  }
  return new Date(this.someDate.getTime());
}

public void setSomeDate(final Date someDate) {
  if (someDate == null) {
    this.someDate = null;
  } else{
  this.someDate = new Date(someDate.getTime());
  }
}



回答3:


Depending on you use-case you could return someDate.getTime() without wrapping it in a Date.




回答4:


Wait a minute... by copying the object within the getSomeDate and setSomeDate methods we are not eliminating the security risk since the changed object comes back through the setSomeDate and copies preserve the changed values. It would be necessary to remove setSomeDate in order to solve this kind of security issue, or do not worry at all about it.



来源:https://stackoverflow.com/questions/7932489/findbugs-issues-with-mutability-of-date-object-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!