Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ccccff
public final class MutableDemo {

    // java.net.HttpCookie is mutable
    public void copyMutableInput(HttpCookie cookie) {
        if (cookie == null) {
            throw new NullPointerException();
        }

        // create copy
        cookie = cookie.clone();

        //check if cookie has expired
        if(cookie.hasExpired())
        {
          //cookie is no longer valid, handle condition
        }

        doLogic(cookie);
    }
}

At times, the copy constructor or the clone method returns a shallow copy of the original instance. For example, invocation of clone() on an array results in creation of an array instance that shares references to the same elements as the original instance. A deep copy that involves element duplication can be created as shown below.

Code Block
bgColor#ccccff

    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);
}

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 xyz. In order to copy mutable inputs having a non-final or interface type, the following approaches may be employed.

Code Block
bgColor#ccccff

// 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);
}

References

Secure Coding in Java http://java.sun.com/security/seccodeguide.html