Findbugs issues with mutability of Date object in Java

ManuPK picture ManuPK · Oct 28, 2011 · Viewed 12.2k times · Source

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?

Answer

Martin Bluemel picture Martin Bluemel · Nov 5, 2013

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());
  }
}