复制对象中的值到另一个对象/全新的对象中
原对象和目标对想的属性名称和属性类型形同的字段可成功赋值:
package com.etc.pbcs.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author: zyh * @time: 2020-08-25 15:56 */ public class ObjectUtils { public static final Logger LOGGER = LoggerFactory.getLogger(ObjectUtils.class); /** * 复制对象中的值到另一个全新对象中 * * @param src * @param tarClazz * @throws Exception * @author zyh * @since JDK 1.8 */ public static <T> T copyObjectFieldToNewObj(Object src, Class<T> tarClazz) throws Exception { try { T t = tarClazz.getConstructor().newInstance(); if (src == null) { return t; } return copyObjectFieldContainsFather(src, t); } catch (Exception e) { LOGGER.error("复制对象中的值到另一个全新对象中错误:" + e.getMessage(), e); throw new PBCSUtilException("object copy to new object error", e); } } /** * 复制对象中的值到另一个对象中 * * @param src * @param tar * @throws Exception * @author zyh * @since JDK 1.8 */ public static <T> T copyObjectFieldContainsFather(Object src, T tar) throws Exception { if (src == null || tar == null) { return tar; } try { Class<?> clazz = src.getClass(); List<Field> fields = new ArrayList<>(); fields.addAll(Arrays.asList(clazz.getDeclaredFields())); if (!"java.lang.Object".equals(clazz.getSuperclass().getTypeName())) { fields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields())); } Class<?> tarClazz = tar.getClass(); List<Field> tarFields = new ArrayList<>(); tarFields.addAll(Arrays.asList(tarClazz.getDeclaredFields())); if (!"java.lang.Object".equals(tarClazz.getSuperclass().getTypeName())) { tarFields.addAll(Arrays.asList(tarClazz.getSuperclass().getDeclaredFields())); } for (Field srcField : fields) { srcField.setAccessible(true); String name = srcField.getName(); Object value = srcField.get(src); if ("serialVersionUID".equals(name) || value == null) { continue; } for (Field tarField : tarFields) { tarField.setAccessible(true); if (name.equalsIgnoreCase(tarField.getName())) { tarField.set(tar, value); break; } } } } catch (Exception e) { LOGGER.error("复制对象中的值到另一个对象错误:" + e.getMessage(), e); throw new Exception("object copy to existing object error", e); } return tar; } }
迎风少年