Returning a reference to a mutable object value stored in one of the object's fields exposes the internal representation of the object. If instances are accessed by untrusted code, and unchecked changes to the mutable object would compromise security or other important properties, you will need to do something different. Returning a new copy of the object is better approach in many situations.
返回对象字段之一中存储的可变对象值的引用将公开该对象的内部表示形式。如果实例被不可信的代码访问,并且对可变对象的未经检查的更改会危及安全性或其他重要属性,那么您需要做一些不同的事情。在许多情况下返回对象的新副本是更好的方法。
This code stores a reference to an externally mutable object into the internal representation of the object. If instances are accessed by untrusted code, and unchecked changes to the mutable object would compromise security or other important properties, you will need to do something different. Storing a copy of the object is better approach in many situations.
此代码将对外部可变对象的引用存储到对象的内部表示中。如果实例被不可信的代码访问,并且对可变对象的未经检查的更改会危及安全性或其他重要属性,那么您需要做一些不同的事情。在许多情况下存储对象的副本是更好的方法。
return createDate==null?null:(Date) createDate.clone();
}
public void setCreateDate(Date createDate) {
this.createDate = createDate==null?null:(Date) createDate.clone();
}
安全返回对象副本
本文讨论了在面向对象编程中,为了防止不可信代码通过对象字段修改内部状态带来的安全风险,建议使用对象副本而非直接引用。介绍了如何通过clone方法创建并返回对象副本。
947

被折叠的 条评论
为什么被折叠?



