Type-safe clone method. - Java Reflection

Java examples for Reflection:Method

Description

Type-safe clone method.

Demo Code


//package com.java2s;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {
    /**//from   w w w . j  a v a 2s. c  o  m
     * Type-safe clone method. Slightly slower than clone(), since we need to
     * use introspection to gain access to clone().
     * <P>
     * Reminder: In Java, clone() is ill-defined. You are generally better off
     * defining your own copy() methods that you can document and customize.
     * 
     * @param <T>
     *            type of instance to clone
     * @param obj
     *            instance to clone
     * 
     * @return result of instance's clone() method
     * @throws RuntimeException
     *             if clone() fails or cannot be called
     */
    @SuppressWarnings("unchecked")
    public static <T extends Cloneable> T clone(T obj) {
        try {
            Method m = obj.getClass().getMethod("clone");
            return (T) m.invoke(obj);
        } catch (SecurityException e) {
            throw new RuntimeException("Not cloneable: " + obj, e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("Not cloneable: " + obj, e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Not cloneable: " + obj, e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException("Not cloneable: " + obj, e);
        }
    }
}

Related Tutorials