转换工具类
public class ConverterUtil {
/**
* 两个对象之间的赋值
* @param source 原对象
* @param dest 目标对象
* @throws IllegalAccessException
* @throws NoSuchMethodException
* @throws InvocationTargetException
*/
public static void getAttribute(E source, E dest) {
//处理自身
final Class clazz = source.getClass();
for (Field field : clazz.getDeclaredFields()) {
try {
fun(field, source, dest);
} catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
e.printStackTrace();
}
}
final Class superclass = source.getClass().getSuperclass();
//处理父类
for (Field field : superclass.getDeclaredFields()) {
//打开私有访问
try {
fun(field, source, dest);
} catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
private static void fun(Field field, E source, E dest) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
//打开私有访问
field.setAccessible(true);
//获取属性
String name = field.getName();
//不处理final类型的字段
if(!Modifier.isFinal(field.getModifiers())) {
if (field.get(source) != null) {
String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1, name.length());
Method method = source.getClass().getMethod(methodName, field.getType());
method.invoke(dest, field.get(source));
}
}
}
}
测试
待测试实体类
- 父类
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class BaseEntity implements Serializable {
private Long id;
private Integer state;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
- 子类
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString(callSuper = true)
public class Province extends BaseEntity {
private String name;
private String area;
private Integer priority;
@Builder
public Province(Long id, Integer state, LocalDateTime createTime, LocalDateTime updateTime, String name, String area, Integer priority) {
super(id, state, createTime, updateTime);
this.name = name;
this.area = area;
this.priority = priority;
}
}
测试代码
public static void main(String[] args) {
final Province source = Province.builder().name("河北省").state(123).build();
final Province dest = Province.builder().id(1001L).area("华北")
.name("河北省").updateTime(LocalDateTime.now()).build();
ConverterUtil.getAttribute(source, dest);
System.out.println(dest);
}
结果