Java中级——保护性拷贝

保护性拷贝

错误示例

如下为Period类,未提供set方法,看起来无法修改其内部属性

final class Period {
    private final Date start;
    private final Date end;

    Period(Date start, Date end) {
        if (start.compareTo(end) > 0) {
            throw new IllegalArgumentException(start + " > " + end);
        }
        this.start = start;
        this.end = end;
    }

    public Date getStart() {
        return start;
    }

    public Date getEnd() {
        return end;
    }
}

但实际上,Date本身是可变的,对Date的修改会导致对Period的修改

Date start = new Date();
Date end = new Date();
Period period = new Period(start, end);
end.setYear(7);

Java8之后应该使用Instant、LocalDateTime、ZonedDateTime代替,但对于可变对象域(即非final类),应该对其进行拷贝

正确示例

需根据传进来的参数创建新的实例,同时创建应在检查之前,从而避免在检查-创建期间参数发生变化,同时这里不调用clone,因为可能传进来的是Date的子类(通过复写clone恶意攻击)

final class Period {
    private final Date start;
    private final Date end;

    Period(Date start, Date end) {
        this.start = new Date(start.getTime());
        this.end = new Date(end.getTime());
        
        if (this.start.compareTo(this.end) > 0) {
            throw new IllegalArgumentException(start + " > " + end);
        }
    }

    public Date getStart() {
        return start;
    }

    public Date getEnd() {
        return end;
    }
}

虽然修改了构造方法,但其get()方法仍然给了外面修改可变内部成员的能力,如下

Date start = new Date();
Date end = new Date();
Period period = new Period(start, end);
period.getEnd().setYear(7);

所以也要对get()方法的返回对象进行拷贝,get方法可以使用clone,因为可以确定内部对象为Date,而不是其子类

final class Period {
    private final Date start;
    private final Date end;
    Period(Date start, Date end) {
        this.start = new Date(start.getTime());
        this.end = new Date(end.getTime());
        if (this.start.compareTo(this.end) > 0) {
            throw new IllegalArgumentException(start + " > " + end);
        }
    }
    public Date getStart() {
        return new Date(start.getTime());
    }
    public Date getEnd() {
        return new Date(end.getTime());
    }
}

需注意:长度非零的数组始终是可变的,需调用clone返回拷贝对象或返回不可变视图,如下

class Test {
    private static final Integer[] VALUES = {1, 2, 3};
    
    public static final List<Integer> UNMODIFIABLE_VALUES = Collections.unmodifiableList(Arrays.asList(VALUES));

    public static final Integer[] values() {
        return VALUES.clone();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值