Fill an array with clones of a single object

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

eg. after:

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

the array rectangleswill contain N different instances Rectangleinitialized with the same coordinates.

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

I suppose there is some kind of library method that does this, but I don't think it is in the JDK, Commons-collection or Guava.

+3
source share
4

, , clone .

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);
}
+2

:

public void fillWithClones(Rectangle[] arr, Rectangle src) {
    for(int xa=0,len=arr.length; xa<len; xa++) { arr[xa]=(Rectangle)src.clone(); }
    }
0

@Chris Jester-Young , .

, - .

  • ? , , ?

  • , ? ? null , ?

, , (public) clone method. , ( !), clone .

0

( , ), - :

(: ):

private static <T> void fillWithClones( T[] array, T object )
{
  try
  {
    @SuppressWarnings("unchecked")
    Class<T> clazz = (Class<T>)object.getClass();
    Constructor<T> c = clazz.getConstructor( object.getClass() );

    try
    {
      for ( int i = 0; i < array.length; i++ )
      {
        array[i] = (T)c.newInstance( object );
      }
    }
    catch ( Exception e )
    {
      // Handle exception or rethrow...
    }
  }
  catch ( NoSuchMethodException e )
  {
    // No copy constructor, try clone option...
  }
}

, .

0

Source: https://habr.com/ru/post/1733628/


All Articles