集册 Java实例教程 深度复制对象

深度复制对象

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

391
深度复制对象

/* 

 * Copyright 2009-2010 junithelper.org. 

 * 

 * Licensed under the Apache License, Version 2.0 (the "License"); 

 * you may not use this file except in compliance with the License. 

 * You may obtain a copy of the License at 

 * 

 *     http://www.apache.org/licenses/LICENSE-2.0 

 * 

 * Unless required by applicable law or agreed to in writing, software 

 * distributed under the License is distributed on an "AS IS" BASIS, 

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 

 * either express or implied. See the License for the specific language 

 * governing permissions and limitations under the License. 

 */

//package com.nowjava;

import java.lang.reflect.Field;

import java.lang.reflect.Modifier;// 来 自 时 代 J a v a - nowjava.com

import java.util.ArrayList;

import java.util.List;


public class Main {

    @SuppressWarnings("unchecked")

    public static <T> T deepCopy(T obj) {

        try {

            if (obj == null) {

                return null;

            }/** 来 自 N o w J a v a . c o m**/

            Class<?> clazz = obj.getClass();

            T clone = (T) clazz.newInstance();

            Field[] fields = clazz.getDeclaredFields();

            for (int i = 0; i < fields.length; i++) {

                Field field = fields[i];

                field.setAccessible(true);

                if (!Modifier.isFinal(field.getModifiers())) {

                    if (field.get(obj) instanceof List<?>) {

                        List<?> copiedList = deepCopyList((List<?>) field

                                .get(obj));

                        field.set(clone, copiedList);

                    } else {

                        field.set(clone, field.get(obj));

                    }

                }

            }

            while (true) {

                if (Object.class.equals(clazz)) {

                    break;

                }

                clazz = clazz.getSuperclass();

                Field[] sFields = clazz.getDeclaredFields();

                for (int i = 0; i < sFields.length; i++) {

                    Field field = sFields[i];

                    field.setAccessible(true);

                    if (!Modifier.isFinal(field.getModifiers())) {

                        if (field.get(obj) instanceof List<?>) {

                            List<?> copiedList = deepCopyList((List<?>) field

                                    .get(obj));

                            field.set(clone, copiedList);

                        } else {

                            field.set(clone, field.get(obj));

                        }

                    }

                }

            }

            return clone;

        } catch (InstantiationException e) {

            return null;

展开阅读全文