@Setter @Getter public class SourceA { private String name; private String text; public SourceA(String name, String text) { this.name = name; this.text = text; } }
@Setter @Getter @ToString public class TargetB {
@FieldMap(name = "name") public LocalDateTime n; private String text; }
Notes field name
@Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface FieldMap { String name() default ""; }
Achieved if the same field type can be assigned, but there may be a different time.
public static void copy(Object source, Object target) throws Exception { Class<?> sourceClass = source.getClass(); Class<?> bClass = target.getClass(); Field[] soutceFields = sourceClass.getDeclaredFields(); Map<String, Object> sourceMap = new HashMap<>(); for (Field field : soutceFields) { field.setAccessible(true); sourceMap.put(field.getName(), field.get(source)); } Field[] targetFields = bClass.getDeclaredFields(); for (Field field : targetFields) { field.setAccessible(true); FieldMap annotation = field.getAnnotation(FieldMap.class); if (annotation != null) { String name = annotation.name(); Object sourceValue = sourceMap.get(name); if (field.getType() == sourceClass.getDeclaredField(name).getType()) { field.set(target, sourceValue); } else { /** * Source of such date field type String, the target type is received date field LocalDateTime */ } continue; } field.set(target, sourceMap.get(field.getName())); } }