Java值对象的复制

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

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

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


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();
			Field[] sourceFields = source.getClass().getDeclaredFields();

			for (Field field : fields) {
				for (Field sourceField : sourceFields) {
					if (field.getName().equals(sourceField.getName())) {
						field.setAccessible(true);
						System.out.println(field.getName() + ", " + sourceField.getName());
						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;
	}

	public static void main(String[] args) {
		UserReq userReq = new UserReq();
		userReq.setUserId("zhangsan");
		userReq.setUserName("张三");
		userReq.setInviterId("001");

		User user = PojoHelper.copy(userReq, User.class);// 将userReq的值给到新对象User
		System.out.println("user.userId = " + user.getUserId());
		System.out.println("user.userName = " + user.getUserName());
	}

}

猜你喜欢

转载自blog.csdn.net/china_3/article/details/81204258
今日推荐