保护性拷贝

来源:互联网 发布:wkwebview js交互 编辑:程序博客网 时间:2024/05/18 00:07

不要以为JAVA是安全的,如果编写的代码不严谨会使得安全性丢掉,当然这不是JAVA的错。

final class Period...{
private final Date start;
private final Date end;
public Period(Date s,Date e)...{
if(s.compareTo(end)>0)...{
throw new IllegalArgumentException(s+" after "+e):
}
start=s;
end=e;
}
public Date start()...{
return start;
}
public Date end()...{
return end;
}
//...
}
public class Test...{
public static void main()...{
Date start=new Date();
Date end=new Date();
Period p=new Period(start,end);

end.setYear(78);// o_o 引用传递带来的问题!!

}
}其实做一个深拷贝就可以了。

public Period(Date s,Date e)...{
start=new Date(s.getTime());
end=new Date(e.getTime());
if(start.compareTo(end)>0)...{
throw new IllegalArgumentException(start+ " after " +end );
}
}不要以为这样以来存在的问题就解决了。

public class Test2...{
public static void main(String[]args)...{
Date start=new Date();
Date end=new Date();
Period p=new Period(start,end);

p.end.setYear(78);// o_o 由于还是引用传递将private 暴露了

}
}
 解决方法:

public Date start()...{
return (Date)start.clone();
}
public Date end()...{
return (Date)end.clone();
}

本文来自CSDN博客,转载处:http://blog.csdn.net/ltbylc/archive/2007/04/03/1550289.aspx