copy Properties between Java Bean - Java Reflection

Java examples for Reflection:Java Bean

Description

copy Properties between Java Bean

Demo Code


//package com.java2s;
import java.lang.reflect.Field;

public class Main {
    public static void main(String[] argv) throws Exception {
        Object dist = "java2s.com";
        Object src = "java2s.com";
        boolean copyNull = true;
        copyProperties(dist, src, copyNull);
    }/*from w  w w  . java 2  s  .co m*/

    public static void copyProperties(Object dist, Object src,
            boolean copyNull) {
        Class classDist = dist.getClass();
        Class classSrc = src.getClass();

        Field fields[] = classSrc.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field filed = fields[i];
            filed.setAccessible(true);//

            try {
                Object srcValue = filed.get(src);
                String fieldName = filed.getName();

                //Field distField = classDist.getField(fieldName);//public feld
                Field distField = classDist.getDeclaredField(fieldName);//all field
                distField.setAccessible(true);
                if (srcValue == null) {
                    if (copyNull) {
                        distField.set(dist, null);
                    }
                } else {
                    distField.set(dist, srcValue);
                }

            } catch (Exception e) {
            }
        }
    }
}

Related Tutorials