Delete comment from: Javarevisited
One more thing that I would like to add Javin regarding the example shown that is..
we should make a copy of remindingDate.getTime() BEFORE checking it against your class invariants. Otherwise an attacker with a reference(long time = remindingDate.getTime();) to your remindingDate could call a .set method on it to change the value after you've checked it's validity.The program should be like ...
public final class ImmutableReminder{
private final Date remindingDate;
public ImmutableReminder (Date remindingDate) {
long incomingTime = remindingDate.getTime()
if(incomingTime < System.currentTimeMillis()){
throw new IllegalArgumentException("Can not set reminder” +
“ for past time: " + remindingDate);
}
this.remindingDate = new Date(incomingTime);
}
public Date getRemindingDate() {
return (Date) remindingDate.clone();
}
}
Mar 5, 2013, 2:06:09 AM
Posted to How to create Immutable Class and Object in Java - Tutorial Example