clone Object - Android java.lang.reflect

Android examples for java.lang.reflect:New Instance

Description

clone Object

Demo Code


import java.lang.reflect.InvocationTargetException;

public class Main{
    public static <T> T cloneObject(T obj)
            throws CloneNotSupportedException {
        T t = null;/*from   w w  w.j  a  v a2 s .  c o m*/
        if (obj != null) {
            if (obj instanceof Cloneable) {
                try {
                    try {
                        t = obj.getClass().getMethod("clone", null)
                                .invoke(obj, null);
                    } catch (InvocationTargetException e) {
                        Throwable cause = e.getCause();
                        if (cause instanceof CloneNotSupportedException) {
                            throw ((CloneNotSupportedException) cause);
                        }
                        throw new Error("Unexpected exception", cause);
                    } catch (IllegalAccessException ex) {
                        throw new IllegalAccessError(ex.getMessage());
                    }
                } catch (NoSuchMethodException ex2) {
                    throw new NoSuchMethodError(ex2.getMessage());
                }
            }
            throw new CloneNotSupportedException();
        }
        return t;
    }
}

Related Tutorials