Defensive copying of Number subclass

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?


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:

  • Cloning of Serializable and Non-Serializable Java Objects

  • You need to clone the object. So your code would look like:

    public final class ImmutableWrapper<T extends Number> {
        private final T value;
    
        public ImmutableWrapper(T value) {
            this.value = value.clone();
        }
    
        public T getValue() {
            return value.clone();
        }
    }
    
    链接地址: http://www.djcxy.com/p/18998.html

    上一篇: 网址不适用于某些曲目

    下一篇: Number子类的防御性复制