如何使用Cloneable类型作为Java泛型类的参数 [英] How to use Cloneable type as parameter to Java generic class

查看:154
本文介绍了如何使用Cloneable类型作为Java泛型类的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用类,需要能够克隆参数类型的对象.下面是一个非常简单的示例.编译器声称看不见对象类型的clone().

I have a generic class that needs to be able to clone objects of the parameter type. A very simple example is below. The compiler claims clone() from the type Object is not visible.

public class GenericTest<T extends Cloneable>
    {
    T obj;
    GenericTest(T t)
        {
        obj = t;
        }
    T getClone()
        {
        // "The method clone() from the type Object is not visible."
        return (T) obj.clone();
        }
    }

我不想让调用者进行克隆,因为要保持对象的完整性还必须进行其他事情.上面的代码只是该问题的说明,没有干扰我必须维护的与克隆对象有关的其他数据.

I'd prefer not to have the caller do the cloning since there are other things that have to happen to maintain the integrity of the object. The code above is just an illustration of the problem without the noise of the other data I have to maintain related to the cloned object.

有没有办法解决这个问题?或者这是Java设计人员考虑合理化其缺点的另一种情况吗?

Is there a way around this or is this another one of those cases where the designers of Java consider rationalizing its shortcomings the equivalent of having none?

推荐答案

Java方面的错误.反思是正确的方法

A mistake on Java's part. Reflection is the right way to go

static Method clone = Object.class.getMethod("clone"); 

static public <T extends Cloneable> 
T clone(T obj)
    return (T) clone.invoke(obj);

这篇关于如何使用Cloneable类型作为Java泛型类的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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