1、定义注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldCopy {
String name() default "";
}
2、编写工具类
import java.lang.reflect.Field;
import java.util.*;
public class FieldCopyUtil {
public static <T,P> void copy(T source , P target) throws NoSuchFieldException, IllegalAccessException {
Class<?> sourceClass = source.getClass();
Class<?> targetClass = target.getClass();
List<Field> sourceFields = new ArrayList<>();
List<Field> targetFields = new ArrayList<>();
getFields(sourceClass,sourceFields);
getFields(targetClass,targetFields);
Map<String,Object> targetMap = getMap(targetFields,target);
Map<String,Object> sourceMap = getMap(sourceFields,source);
Map<String, ? extends Class<?>> sourceFileMap = sourceFields.stream().collect(Collectors.toMap(Field::getName, Field::getType));
for(Field field : targetFields){
field.setAccessible(true);
FieldCopy annotation = field.getAnnotation(FieldCopy.class);
if(annotation != null ){
String name = annotation.name();
if(field.getType() == sourceFileMap.get(name)){
field.set(target,sourceMap.get(name));
}
}
}
}
private static Map<String, Object> getMap(List<Field> fields,Object obj) throws IllegalAccessException {
Map<String, Object> map = new HashMap<>();
for (Field field :fields) {
field.setAccessible(true);
map.put(field.getName(),field.get(obj));
}
return map;
}
private static void getFields(Class<?> aClass, List<Field> fields) {
// 获取子类字段
Field[] declaredFields = aClass.getDeclaredFields();
fields.addAll(Arrays.asList(declaredFields));
// 取父类字段
if (!aClass.getSuperclass().equals(Object.class)){
getFields(aClass.getSuperclass(),fields);
}
}
}
3、使用
例如
类A 中的字段perName 拷贝给类B中的name,
由于字段名不一致,BeanUtils.copyProperties();不能拷贝
在类B的字段name上加上注解@FieldCopy(name="perName ")
最后掉用FieldCopyUtil.copy(A,B)