用泛型克隆 [英] Cloning with generics

查看:452
本文介绍了用泛型克隆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

曾几何时有一个班级:

public class Scope<C extends Cloneable & Comparable<C>> implements Comparable<Scope<C>>, Cloneable, Serializable {

   private C starts;
   private C ends;
   ...

   @SuppressWarnings("unchecked")
   @Override
   public Object clone() {
       Scope<C> scope;
       try {
           scope = (Scope<C>) super.clone();
           scope.setStarts((C) starts.clone()); // The method clone() from the type Object is not visible
           scope.setEnds((C) ends.clone()); // The method clone() from the type Object is not visible
       } catch (CloneNotSupportedException e) {
           throw new RuntimeException("Clone not supported");
       }
       return scope;
   }
}

在对象中我们有:

protected native Object clone() throws CloneNotSupportedException;

并且Cloneable接口是:

And Cloneable interface is:

public interface Cloneable { 
}

我应该如何克隆这个?

推荐答案

我认为当前的绿色答案很糟糕,为什么你会问?


  • 它添加了大量代码

  • 它要求您列出要复制的所有字段并执行此操作

  • 当使用clone()
    时,这不适用于列表(这是HashMap的clone()所说的:返回此HashMap实例的浅表副本:键和值自己没有克隆。)所以你最终手动做(这让我哭)

哦顺便说一下序列化也不好,你可能不得不在整个地方添加Serializable(这也让我哭泣)。

Oh and by the way serialization is also bad, you might have to add Serializable all over the place (this also makes me cry).

那么解决方案是什么:

Java深度克隆库
克隆库很小,开源(apache license)深入克隆对象的java库。对象不必实现Cloneable接口。实际上,这个库可以克隆任何java对象。如果您不希望修改缓存对象或者只是想要创建对象的深层副本,则可以在缓存实现中使用它。

Java Deep-Cloning library The cloning library is a small, open source (apache licence) java library which deep-clones objects. The objects don't have to implement the Cloneable interface. Effectivelly, this library can clone ANY java objects. It can be used i.e. in cache implementations if you don't want the cached object to be modified or whenever you want to create a deep copy of objects.

Cloner cloner=new Cloner();
XX clone = cloner.deepClone(someObjectOfTypeXX);

http://code.google.com/p/cloning/

这篇关于用泛型克隆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆