填充数组与单个对象的克隆 [英] Fill an array with clones of a single object

查看:175
本文介绍了填充数组与单个对象的克隆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是快速简便的方法来填补Java数组与单个对象的克隆?

What is a quick and easy way to fill a Java array with clones of a single object?

例如。后:

Rectangle[] rectangles = new Rectangle[N];
fillWithClones(rectangles, new Rectangle(1, 2, 3, 4));

长方形数组将包含N个不同长方形情况下,具有相同的坐标初始化。

the rectangles array would contain N distinct Rectangle instances, initialised with the same coordinates.

我知道的缺陷Object.clone()在Java中,但在这种情况下,我知道的对象被复制具有非投掷,公共的clone()方法,但可能会或可能不会有一个公共的拷贝构造函数。

I am aware of the flaws of Object.clone() in Java, but in this case I know that the objects to be copied have non-throwing, public clone() methods but may or may not have a public copy constructor.

我猜有一个图书馆法的地方,这样做,但我不认为这是在JDK,共享的集合或番石榴。

I'm guessing there is a library method somewhere that does this, but I don't think it's in the JDK, Commons-collections or Guava.

推荐答案

如果你没有你想在编译时一起工作的具体类型,则必须调用克隆反射法。

If you don't have the specific type you want to work with at compile time, you will have to invoke the clone method by reflection.

private static <T> T cloneByReflection(T object) {
    try {
        return (T) object.getClass().getMethod("clone").invoke(object);
    } catch (Exception e) {
        return null;    // or whatever you want to do
    }
}

public static <T> void fillWithClones(T[] array, T template) {
    for (int i = 0; i < array.length; ++i)
        array[i] = cloneByReflection(template);
}

这篇关于填充数组与单个对象的克隆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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