利用反射转移实例数据
1、自定义注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* annotation to target class field
* @Author tan.mu.jin
* @Date 2022/1/13
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldMapper {
/**
* source field name
*/
String value() default "";
}
2、工具类
import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSONObject;
import com.lingyi.financedata.annotation.FieldMapper;
import javax.validation.constraints.NotNull;
import java.lang.reflect.Field;
/**
* @Author tan.mu.jin
* @Date 2022/1/13
*/
public class BeanUtil {
/**
* Copy source instance field value to target instance field.<br/><br/>
* Target class field is must annotation by FieldMapper
* @param source source instance
* @param target target instance
*/
public static void copyProperties(@NotNull Object source, @NotNull Object target){
Assert.notNull(source, "source is must not null");
Assert.notNull(target, "target is must not null");
Field[] sourceFields = source.getClass().getDeclaredFields();
JSONObject sourceFieldMap = new JSONObject(sourceFields.length);
for(Field field : sourceFields){
String fieldName = field.getName();
field.setAccessible(true);
Object fieldValue = null;
try {
fieldValue = field.get(source);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
sourceFieldMap.put(fieldName, fieldValue);
}
Field[] targetFields = target.getClass().getDeclaredFields();
for (Field field : targetFields) {
boolean isPresent = field.isAnnotationPresent(FieldMapper.class);
if(isPresent){
field.setAccessible(true);
String annotationValue = field.getAnnotation(FieldMapper.class).value();
try {
Object sourceFieldValue = sourceFieldMap.get(annotationValue);
Assert.notNull(sourceFieldValue, "can not find source class field: {}", annotationValue);
field.set(target, sourceFieldValue);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
}
3、调用工具方法
UserEntity entity = new UserEntity("userName", "password", 20);
//UserDto的字段上应使用@FieldMapper注解,value对应UserEntity的字段名称
UserDto dto = new UserDto();
//调用工具方法,将entity的字段值赋给dto对应字段
BeanUtil.copyProperties(entity, dto);