...
| Code Block | ||
|---|---|---|
| ||
public void deepCopy(int[] ints, HttpCookie[] cookies) {
if (ints == null || cookies == null) {
throw new NullPointerException();
}
// shallow copy
int[] intsCopy = ints.clone();
// deep copy
HttpCookie[] cookiesCopy = new HttpCookie[cookies.length];
for (int i = 0; i < cookies.length; i++) {
// manually create copy of each element in array
cookiesCopy[i] = cookies[i].clone();
}
doLogic(intsCopy, cookiesCopy);
}
|
| Wiki Markup |
|---|
When the mutable input type is non-final, a malicious subclass may override the {{clone}} method. This is a serious issue unless the non-final input defends against it |
. (See \[[Guideline 2-1 Create a copy of mutable inputs and outputs|http://java.sun.com/security/seccodeguide.html]\].) In order to copy mutable inputs having a non-final or interface type, the following approaches may be employed. |
| Code Block | ||
|---|---|---|
| ||
// java.util.ArrayList is mutable and non-final
public void copyNonFinalInput(ArrayList list) {
// create new instance of declared input type
list = new ArrayList(list);
doLogic(list);
}
// java.util.Collection is an interface
public void copyInterfaceInput(Collection collection) {
// convert input to trusted implementation
collection = new ArrayList(collection);
doLogic(collection);
}
|
...