集册 Java实例教程 在Java Bean之间复制属性

在Java Bean之间复制属性

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

471
在Java Bean之间复制属性


//package com.nowjava;

import java.lang.reflect.Field;/*时 代 J a v a 提 供*/


public class Main {

    public static void main(String[] argv) throws Exception {

        Object dist = "nowjava.com";

        Object src = "nowjava.com";

        boolean copyNull = true;

        copyProperties(dist, src, copyNull);

    }


    public static void copyProperties(Object dist, Object src,

            boolean copyNull) {// 来自 时 代 J a v a 公 众 号 - N o w J a v  a . c o m

        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) {

                    
展开阅读全文