防御性复制Number子类

时间:2014-02-12 10:43:39

标签: java generics

请考虑以下示例:

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

为了使这个类不可变,我必须防御性地复制传递给构造函数的任何可变参数,并创建由公共方法返回的内部可变对象的副本。

这可能吗?如果没有,是否有任何解决方法?

2 个答案:

答案 0 :(得分:3)

由于所有Number都是Serializable,您可以serializing/deserializing创建副本。

也许你可以使用apache commons-lang的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);
    }
}

或者如果你想自己实现它,请看看:

答案 1 :(得分:0)

您需要克隆该对象。所以你的代码看起来像是:

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