我正在上一门不变的课。下面是我的不可变类,请告诉我它是完全不可变的,或者如果我缺少某些东西,或者它的不可变性可以通过任何方式分解,那么请告知。
public final class ImmutableReminder{
private final Date remindingDate;
public ImmutableReminder (Date remindingDate) {
if(remindingDate.getTime() < System.currentTimeMillis()){
throw new IllegalArgumentException("Can not set reminder” +
“ for past time: " + remindingDate);
}
this.remindingDate = new Date(remindingDate.getTime());
}
public Date getRemindingDate() {
return (Date) remindingDate.clone();
}
}
最佳答案
在根据您的类不变式检查它之前,您应该制作一个hintingDate.getTime()的副本。否则,引用您的hintingDate的攻击者可以在检查其有效性之后对其调用.set方法来更改该值。
很长的时间= hintingDate.getTime();
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();
}
}