博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java反射bean to bean
阅读量:4597 次
发布时间:2019-06-09

本文共 1744 字,大约阅读时间需要 5 分钟。

/**    * Copyright © 2018 fwz Info. Tech Ltd. All rights reserved. *  * @Package: com.sm.utils  * @author: 冯文哲    * @date: 2018年7月3日 上午11:53:09  */package com.sm.utils; import java.beans.BeanInfo;import java.beans.Introspector;import java.beans.PropertyDescriptor;/** *  * @author: 冯文哲    * @date: 2018年7月3日 上午11:53:09 *  */public class CopyUtils {	/**	 * 	 * @Description:复制属性 bean to bean	 * @author: 冯文哲   	 * @date: 2018年7月3日 上午11:54:09	 * @param source 数据元Bean	 * @param dest 目标实体bean	 * @throws Exception	 *	 */	 public static void Copy(Object baseBean, Object targetBean) throws Exception {	        // 获取属性	        BeanInfo sourceBean = Introspector.getBeanInfo(baseBean.getClass(),Object.class);	        PropertyDescriptor[] sourceProperty = sourceBean.getPropertyDescriptors();	 	        BeanInfo destBean = Introspector.getBeanInfo(targetBean.getClass(),Object.class);	        PropertyDescriptor[] destProperty = destBean.getPropertyDescriptors();	 	        try {	            for (int i = 0; i < sourceProperty.length; i++) {	                	                for (int j = 0; j < destProperty.length; j++) {	                    	                    if (sourceProperty[i].getName().equals(destProperty[j].getName())  && sourceProperty[i].getPropertyType() == destProperty[j].getPropertyType()) {	                        // 调用source的getter方法和dest的setter方法	                        destProperty[j].getWriteMethod().invoke(targetBean,sourceProperty[i].getReadMethod().invoke(baseBean));	                        break;	                    }	                }	            }	        } catch (Exception e) {	            throw new Exception("属性复制失败:" + e.getMessage());	        }	    }	}

  

转载于:https://www.cnblogs.com/fengwenzhee/p/9258267.html

你可能感兴趣的文章
java学习 - 读代码记录2
查看>>
mysql,mycat的demo
查看>>
MongoDB--CSharp Driver Quickstart .
查看>>
Android 开发框架【转】
查看>>
ansible基础-Jinja2模版 | 测试
查看>>
数字图像处理实验(5):PROJECT 04-01 [Multiple Uses],Two-Dimensional Fast Fourier Transform ...
查看>>
sqlite3:深入理解sqlite3_stmt 机制
查看>>
一个注释版的查取列表信息
查看>>
使用Ctex总结1
查看>>
ios关闭自动更新
查看>>
10 款非常棒的CSS代码格式化工具推荐
查看>>
【BZOJ2298】[HAOI2011]problem a
查看>>
【转】关于Jmeter3.0,你必须要知道的5点变化
查看>>
OJ使用心得
查看>>
day6_time模块和datetime模块
查看>>
AppUi自动化框架tool.py代码
查看>>
Oracle物理文件分类:
查看>>
请别随意关闭默认共享
查看>>
Linux CentOS中防火墙的关闭及开启端口
查看>>
机器学习中的数学(1)-回归(regression)、梯度下降(gradient descent)
查看>>