Performs a shallow copy of all fields defined by the class of src and all super classes. - Java Reflection

Java examples for Reflection:Field

Description

Performs a shallow copy of all fields defined by the class of src and all super classes.

Demo Code

/*//from w  ww.jav  a2 s .  c  o m
 * Copyright (c) 2012 Data Harmonisation Panel
 * 
 * All rights reserved. This program and the accompanying materials are made
 * available under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this distribution. If not, see <http://www.gnu.org/licenses/>.
 * 
 * Contributors:
 *     HUMBOLDT EU Integrated Project #030962
 *     Data Harmonisation Panel <http://www.dhpanel.eu>
 */
//package com.java2s;

import java.lang.reflect.Field;

import java.lang.reflect.Modifier;

public class Main {
    /**
     * Performs a shallow copy of all fields defined by the class of src and all
     * superclasses.
     * 
     * @param <T> the type of the source and destination object
     * @param src the source object
     * @param dst the destination object
     * @throws IllegalArgumentException if a field is unaccessible
     * @throws IllegalAccessException if a field is not accessible
     */
    public static <T> void shallowEnforceDeepProperties(T src, T dst)
            throws IllegalArgumentException, IllegalAccessException {
        Class<?> cls = src.getClass();
        shallowEnforceDeepProperties(cls, src, dst);
    }

    private static <T> void shallowEnforceDeepProperties(Class<?> cls,
            T src, T dst) throws IllegalArgumentException,
            IllegalAccessException {
        if (cls == Object.class || cls == null) {
            return;
        }

        Field[] fields = cls.getDeclaredFields();
        for (Field f : fields) {
            if (Modifier.isStatic(f.getModifiers())
                    || Modifier.isFinal(f.getModifiers())) {
                continue;
            }

            boolean accessible = f.isAccessible();
            f.setAccessible(true);
            try {
                Object val = f.get(src);
                f.set(dst, val);
            } finally {
                f.setAccessible(accessible);
            }
        }

        shallowEnforceDeepProperties(cls.getSuperclass(), src, dst);
    }
}

Related Tutorials