Java 数字子类的防御性复制 请考虑以下例子: 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; } } 公共最终类ImmutableWrapper{ 私人最终T值; 公共ImmutableWrapper(T值){ //Number的子类可以是可变的 //那么,如何防御性地复制价值呢? 这个值=值; } 公共T getValue(){ //这里也一样:如何返回副本? 返回值; } }

Java 数字子类的防御性复制 请考虑以下例子: 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; } } 公共最终类ImmutableWrapper{ 私人最终T值; 公共ImmutableWrapper(T值){ //Number的子类可以是可变的 //那么,如何防御性地复制价值呢? 这个值=值; } 公共T getValue(){ //这里也一样:如何返回副本? 返回值; } },java,generics,Java,Generics,为了使这个类不可变,我必须防御性地复制传递给构造函数的任何可变参数,并创建公共方法返回的内部可变对象的副本 这可能吗?如果没有,是否有解决方法?您需要克隆对象。因此,您的代码如下所示: public final class ImmutableWrapper<T extends Number> { private final T value; public ImmutableWrapper(T value) { this.value = value.c

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


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

您需要克隆对象。因此,您的代码如下所示:

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();
    }
}
公共最终类ImmutableWrapper{
私人最终T值;
公共ImmutableWrapper(T值){
this.value=value.clone();
}
公共T getValue(){
返回值.clone();
}
}

由于所有的
编号都是
s,您可以通过
序列化/反序列化
来创建副本

也许你可以使用ApacheCommonsLang的

公共最终类ImmutableWrapper{
私人最终T值;
公共ImmutableWrapper(T值){
//Number的子类可以是可变的
//那么,如何防御性地复制价值呢?
this.value=SerializationUtils.clone(value);
}
公共T getValue(){
//这里也一样:如何返回副本?
返回SerializationUtils.clone(值);
}
}
或者,如果您想自己实现它,请查看:


但是
T扩展了Number
并且
java.lang.Number
没有公共方法
clone
。这个示例是如何编译的?Number也没有实现Cloneable。只是将其粘贴到eclipse中。编译器对
value.clone()
不满意,因为
clone()
对象上不可见。那么库的克隆呢?“有什么缺点吗?”保罗同意上面的答案。他是对的,克隆方法是受保护的。你为什么要这样做?在javadoc中声明,如果数字发生了变化,那么类的行为在多线程上下文中是未定义的,这难道不更简单吗?@assylias例如,我在Guava的文章中看到了一条关于在javadoc中将可变对象传递给构造函数的警告。无论如何,这是我最后的选择。除非你害怕恶意代码弄乱你的代码,否则这是一个完全合理的选择。
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);
    }
}