问题
I have a java class:
class MyObj{
private Timestamp myDate;
public Timestamp getMyDate(){
return mydate;
}
...
}
when I check it by Findbugs, it says:
Bug kind and pattern: EI - EI_EXPOSE_REP May expose internal representation by returning reference to mutable object
so, what is the better way to write the getter
for Date
and Timestamp
types in Java?
回答1:
Date
and Timestamp
are both mutable, so returning a reference to your Timestamp
means the caller can change the internal state of your class. That's only a problem if it's a problem, if that makes sense; if you mean for the caller to be able to modify the state of your object (by modifying the state of the instance field you're returning), that's okay, though it can be the source of relatively subtle bugs. Often, though, you don't mean to allow the caller to do that; hence FindBugs flagging it up.
You have a couple of choices if you want to avoid exposing a reference to a mutable object:
Clone the object when returning it (a "defensive copy"), so that the caller gets a copy, not the original:
public Timestamp getMyDate(){ return new Timestamp(mydate.getTime()); }
Return an immutable type or a primitive instead of a mutable one, for instance:
public long getMyDate(){ return mydate.getTime(); }
Don't use a mutable object at all. For instance, instead of
Timestamp
, you might useLocalDateTime
orZonedDateTime
from java.time, e.g.:class MyObj{ private LocalDateTime myDate; public LocalDateTime getMyDate(){ return mydate; } // ... }
If you need to update the date in your class (let's use the example of adding a day), instead of mutating the object, you replace it with a new one:
this.mydate = this.myDate.plusDays(1);
回答2:
Return a defensive copy rather than original so that the getter accessor can't modify your actual Timestamp .
public Timestamp getMyDate(){
return new Timestamp(mydate.getTime());
}
来源:https://stackoverflow.com/questions/45050480/returning-mutable-member-variables-date-timestamp-using-getter-functions-in-ja