类型

欢马劈雪     最近更新时间:2020-01-02 10:19:05

447
类型安全的克隆方法。
/**nowjava - 时代Java**/


//package com.nowjava;


import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;


public class Main {

    /**

     * 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) {// 来自 nowjava.com

            throw new RuntimeException("Not cloneable: " + obj, e);

        } catch (IllegalAccessException e) {

            throw 
展开阅读全文