Please consider the following example:
public final class ImmutableWrapper<T extends Number> {
private final T value;
public ImmutableWrapper(T value) {
// a subclass of Number may be mutable
// so, how to defensively copying the value?
this.value = value;
}
public T getValue() {
// the same here: how to return a copy?
return value;
}
}
In order to make this class immutable, I must defensively copy any mutable parameter passed to the constructor and create copies of internal mutable objects returned by public methods.
Is this possible? If not, is there any workaround?
Defensive copying is concerned with protecting mutable objects e.g. objects who's state can be modified by the user.
Java Practices->Defensive copying. A mutable object is simply an object which can change its state after construction. For example, StringBuilder and Date are mutable objects, while String and Integer are immutable objects. A class may have a mutable object as a field.
Since all Number
s are Serializable
you can create copies by serializing/deserializing
them.
Maybe you can use apache commons-lang's SerializationUtils.clone(Serializable)
.
public final class ImmutableWrapper<T extends Number> {
private final T value;
public ImmutableWrapper(T value) {
// a subclass of Number may be mutable
// so, how to defensively copying the value?
this.value = SerializationUtils.clone(value);
}
public T getValue() {
// the same here: how to return a copy?
return SerializationUtils.clone(value);
}
}
or if you want to implement it by yourself take a look at:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With