View Javadoc

1   /*
2   Copyright (C) 2000 - 2007 Grid Systems, S.A.
3   
4   This program is free software; you can redistribute it and/or modify
5   it under the terms of the GNU General Public License, version 2, as
6   published by the Free Software Foundation.
7   
8   This program is distributed in the hope that it will be useful,
9   but WITHOUT ANY WARRANTY; without even the implied warranty of
10  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11  GNU General Public License for more details.
12  
13  You should have received a copy of the GNU General Public License
14  along with this program; if not, write to the Free Software
15  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16  */
17  package com.gridsystems.innergrid.api;
18  
19  import java.lang.reflect.Array;
20  import java.lang.reflect.InvocationTargetException;
21  import java.lang.reflect.Method;
22  
23  import org.apache.axis.InternalException;
24  
25  /**
26   * Cloning utilities.
27   *
28   * @author dsanchez
29   * @author Xmas (Generics)
30   */
31  public final class CloneUtils {
32    /**
33     * Private constructor.
34     */
35    private CloneUtils() {
36    }
37  
38    /**
39     * Clone array and its contents.
40     * @param source Original Array
41     * @param <T> Type of the Array to Clone.
42     * @return Clone of <code>source</code>.
43     * @throws CloneNotSupportedException if the array cannot be cloned
44     */
45    @SuppressWarnings("unchecked")
46    public static <T> T[] cloneArray(T[] source)
47      throws CloneNotSupportedException {
48      if (source == null) {
49        return null;
50      }
51      Class theClass = source.getClass().getComponentType();
52      if (!Cloneable.class.isAssignableFrom(theClass)) {
53        return source.clone();
54      }
55      int length = Array.getLength(source);
56  
57      T[] newArray = (T[])Array.newInstance(theClass, length);
58  
59      try {
60        Method mclone = theClass.getMethod("clone");
61        for (int i = 0; i < length; i++) {
62          if (source[i] == null) {
63            newArray[i] = null;
64          } else {
65            newArray[i] = (T)mclone.invoke(source[i]);
66          }
67        }
68      } catch (InvocationTargetException e) {
69        throw new InternalException(e);
70      } catch (Exception e) {
71        throw new CloneNotSupportedException(e.toString());
72      }
73      return newArray;
74    }
75  
76  
77  }