Java Reference
In-Depth Information
// May be safely invoked by untrusted caller having read ability
public Mutable getMutable() {return mutable;}
In this class, invoking the getter method getArray() does not allow modification of
the private internal state of the class, in accordance with “OBJ05-J. Defensively copy
private mutable class members before returning their references” [Long 2012]. However,
an untrusted invoker may call the method setArray() and modify the Mutable object.
Compliant Solution
Ingeneral,sensitiveclassescanbetransformedintosafe-viewobjectsbyprovidingappro-
priate wrappers for all methods defined by the core interface, including the mutator meth-
ods. The wrappers for the mutator methods must throw an UnsupportedOperationEx-
ception so that clients cannot perform operations that affect the immutability property of
the object.
This compliant solution adds a setArray() method that overrides the Mut-
able.setArray() method and prevents mutation of the Mutable object:
Click here to view code image
class MutableProtector extends Mutable {
@Override
public int[] getArray() {
return super.getArray().clone();
}
@Override
public void setArray(int[] i) {
throw new UnsupportedOperationException();
}
}
// ...
private Mutable mutable = new MutableProtector();
// May be safely invoked by untrusted caller having read ability
public Mutable getMutable() {return mutable; }
The MutableProtector wrapper class overrides the getArray() method and clones
the array. Although the calling code gets a copy of the mutable object's array, the original
arrayremains unchangedandinaccessible. Theoverriding setArray() methodthrowsan
Search WWH ::




Custom Search