自己写的一个相同属性copy的方法

前段时间写项目的时候需要把2个不同的类中相同属性的值复制一下,虽然已经包做了这项事情,但是不知道会不会符合自己的要求,所以自己写了一个,只是最简单的,而且参考了网上的一些其他人的代码:

public class CopyUtil {
	/**
	 * 把from对象中的属性值copy给to对象中属性值相同的 </br>
	 * (简单copy,只能copy基本数据类型的属性)
	 * @param from
	 * @param to
	 */
	public static void copy(Object from,Object to){
		Method[] fromMethods = from.getClass().getDeclaredMethods();
		Method[] toMethods = to.getClass().getDeclaredMethods();
		for (Method fromMethod : fromMethods) {
			//获取from对象的get方法
			String fromMethodName = fromMethod.getName();
			if(!fromMethodName.contains("get")){
				continue;
			}
			String fromstr = fromMethodName.substring(3);
			String fromPro = fromstr.substring(0, 1).toLowerCase()+fromstr.substring(1);
			for (Method toMethod : toMethods) {
				//获取to对象的set方法
				String toMethodName = toMethod.getName();
				if(!toMethodName.contains("set")){
					continue;
				}
				String tostr = toMethodName.substring(3);
				String toPro = tostr.substring(0, 1).toLowerCase()+tostr.substring(1);
				//属性名相同则copy
				if(fromPro.equals(toPro)){
					  try {
						Object value = fromMethod.invoke(from, new Object[0]);
						if(value == null){
							continue;
						}
						toMethod.invoke(to, new Object[]{value});
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (InvocationTargetException e) {
						e.printStackTrace();
					}  
					  
				}
			}
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值