保护性拷贝
来源:互联网 发布:caffe faster rcnn 编辑:程序博客网 时间:2024/05/16 03:41
不要以为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 引用传递带来的问题!!
}
}
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 );
}
}
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 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();
}
return (Date)start.clone();
}
public Date end()...{
return (Date)end.clone();
}
- 保护性拷贝
- 保护性拷贝
- 保护性拷贝(defensive copy)
- 【java】保护性拷贝的重要性
- Effective Java —— 保护性拷贝
- java保护性拷贝(effective java)
- (39):必要时进行保护性拷贝
- 第39条:必要时进行保护性拷贝
- 第39条:必要时进行保护性拷贝
- 第39条 : 必要时进行保护性拷贝
- 2015062706 - EffactiveJava笔记 - 第39条 必要时进行保护性拷贝
- Effective Java 读书笔记——39:必要时进行保护性拷贝
- 保护性拷贝和不可变视图的学习,更面向对象的设计
- 保护性 copy
- BASH的保护性编程技巧
- BASH的保护性编程技巧
- BASH的保护性编程技巧
- 男性多吃苹果可保护性功能
- 为什么要使用接口编程
- 通用高效分页存储过程代码--针对单一字段排序分页
- 卡巴使用技巧
- 看完9个笑话 顿悟9个人生道理
- [TODO]
- 保护性拷贝
- 出师未捷...
- ereport输出问题
- oracle 9i 服务的分类
- 倒数计时类
- ajax和XMLHTTP原理
- ASP.NET编程中的十大技巧
- Lightbox类
- 美女