Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defensive copying of Number subclass

Tags:

java

generics

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?

like image 557
Paolo Fulgoni Avatar asked Feb 12 '14 10:02

Paolo Fulgoni


People also ask

What is defensive copying?

Defensive copying is concerned with protecting mutable objects e.g. objects who's state can be modified by the user.

How will you define the defensive method in Java?

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.


1 Answers

Since all Numbers 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:

  • Cloning of Serializable and Non-Serializable Java Objects
like image 71
René Link Avatar answered Sep 22 '22 17:09

René Link