| 1 | /*
|
|---|
| 2 | * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
|
|---|
| 3 | *
|
|---|
| 4 | * Copyright 2008 jOpenDocument, by ILM Informatique. All rights reserved.
|
|---|
| 5 | *
|
|---|
| 6 | * The contents of this file are subject to the terms of the GNU
|
|---|
| 7 | * General Public License Version 3 only ("GPL").
|
|---|
| 8 | * You may not use this file except in compliance with the License.
|
|---|
| 9 | * You can obtain a copy of the License at http://www.gnu.org/licenses/gpl-3.0.html
|
|---|
| 10 | * See the License for the specific language governing permissions and limitations under the License.
|
|---|
| 11 | *
|
|---|
| 12 | * When distributing the software, include this License Header Notice in each file.
|
|---|
| 13 | *
|
|---|
| 14 | */
|
|---|
| 15 |
|
|---|
| 16 | package org.jopendocument.util;
|
|---|
| 17 |
|
|---|
| 18 | import java.lang.reflect.Method;
|
|---|
| 19 |
|
|---|
| 20 | public final class CopyUtils {
|
|---|
| 21 |
|
|---|
| 22 | /**
|
|---|
| 23 | * Copy the passed object. First tries to clone() it, otherwise tries with a copy constructor.
|
|---|
| 24 | *
|
|---|
| 25 | * @param <E> the type of object to be copied.
|
|---|
| 26 | * @param object the object to be copied, can be <code>null</code>.
|
|---|
| 27 | * @return a copy of <code>object</code>, or <code>null</code> if object was
|
|---|
| 28 | * <code>null</code>.
|
|---|
| 29 | * @throws IllegalStateException if the object can't be copied.
|
|---|
| 30 | */
|
|---|
| 31 | @SuppressWarnings("unchecked")
|
|---|
| 32 | public static final <E> E copy(E object) {
|
|---|
| 33 | if (object == null)
|
|---|
| 34 | return null;
|
|---|
| 35 |
|
|---|
| 36 | if (object instanceof Cloneable) {
|
|---|
| 37 | final Method m;
|
|---|
| 38 | try {
|
|---|
| 39 | m = object.getClass().getMethod("clone");
|
|---|
| 40 | } catch (NoSuchMethodException e) {
|
|---|
| 41 | throw ExceptionUtils.createExn(IllegalStateException.class, "Cloneable w/o clone()", e);
|
|---|
| 42 | }
|
|---|
| 43 | try {
|
|---|
| 44 | return (E) m.invoke(object);
|
|---|
| 45 | } catch (Exception e) {
|
|---|
| 46 | throw ExceptionUtils.createExn(IllegalStateException.class, "clone() failed", e);
|
|---|
| 47 | }
|
|---|
| 48 | } else {
|
|---|
| 49 | try {
|
|---|
| 50 | return (E) object.getClass().getConstructor(new Class[] { object.getClass() }).newInstance(new Object[] { object });
|
|---|
| 51 | } catch (Exception e) {
|
|---|
| 52 | throw ExceptionUtils.createExn(IllegalStateException.class, "Copy constructor failed", e);
|
|---|
| 53 | }
|
|---|
| 54 | }
|
|---|
| 55 | }
|
|---|
| 56 |
|
|---|
| 57 | }
|
|---|