保护性拷贝(defensive copy)
package com.starfuxks; import java.util.Date; public class PseudoDefensiveCopyClass { private Date date; public PseudoDefensiveCopyClass(Date date) { this.date = date; } public Date getDate() { return date; } }
表面上看,这个类的private变量无法被修改。但实际上是错误的,getDate反悔了关于date的引用,然后获得引用后可以直接修改date的值。所以要让date无法被修改,最简单的方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
package
com.starfuxks;
import
java.util.Date;
public
class
PseudoDefensiveCopyClass {
private
Date date;
public
PseudoDefensiveCopyClass(Date date) {
this .date = date;
}
public
Date getDate() {
return
new
Date(date);
}
} |