Java值对象的复制

VO、PO、DTO、BO之间往往需要互转,

转换时,相同的字段值直接复制到新的对象上。

package com.helloworld.pojo;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class PojoHelper {

	/**
	 * 将一个对象的值拷贝至另一个对象
	 * 
	 * @param source
	 *            数据来源的对象
	 * @param clazz
	 *            要转换的类型
	 * @return
	 */
	public static <T> T copy(Object source, Class<T> clazz) {
		T result = null;
		try {
			result = clazz.newInstance();
			Field[] fields = clazz.getDeclaredFields();
			if(source == null) {
				return null;
			}
			Field[] sourceFields = source.getClass().getDeclaredFields();

			for (Field field : fields) {
				for (Field sourceField : sourceFields) {
					if (field.getName().equals(sourceField.getName())) {
						field.setAccessible(true);
						if(Modifier.isStatic(field.getModifiers())) {
							continue;
						}
						String name = field.getName();

						String firstLetter = name.substring(0, 1).toUpperCase(); // 将属性的首字母转换为大写
						String getMethodName = "get" + firstLetter + name.substring(1);
						String setMethodName = "set" + firstLetter + name.substring(1);

						// 获取方法对象
						Method getMethod = source.getClass().getMethod(getMethodName, new Class[] {});
						Method setMethod = clazz.getMethod(setMethodName, new Class[] { field.getType() });// 注意set方法需要传入参数类型

						// 调用get方法获取旧的对象的值
						Object value = getMethod.invoke(source, new Object[] {});
						// 调用set方法将这个值复制到新的对象中去
						setMethod.invoke(result, new Object[] { value });

					}
				}
			}
		} catch (SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchMethodException
				| InvocationTargetException | InstantiationException e) {
			e.printStackTrace();
		}
		return result;
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值