使用BeanUtils
@Data
@Builder
public class People {
private String name;
private Integer age;
private Date date;
public People(String name, Integer age, Date date) {
this.name = name;
this.age = age;
this.date = date;
}
}
@Data
@ToString
public class User {
private String name;
private Integer age;
private Date date;
}
People people = new People("zhangsan", 12, date);
User user = new User();
BeanUtils.copyProperties(people,user);
重写GET改变User中date返回类型
@Data
@ToString
public class User {
private String name;
private Integer age;
private Date date;
public String getDate() {
if (date != null) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
return simpleDateFormat.format(date);
}
return "";
}
}
底层实现
public static void main(String[] args) throws Exception {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = simpleDateFormat.parse("2021-12-07");
People people = new People("zhangsan", 12, date);
User user = new User();
Class<?> clzPeople = people.getClass();
Class<?> clzUser = user.getClass();
Field[] fields = clzPeople.getDeclaredFields();
for (Field field : fields) {
System.out.println(field.getGenericType());
String name = field.getName();
String methodName = Character.toUpperCase(name.charAt(0)) + name.substring(1);
System.out.println(methodName);
Method method = clzPeople.getMethod("get" + methodName);
Object arg = method.invoke(people);
System.out.println(arg);
Type t = method.getAnnotatedReturnType().getType();
Method method1 = clzUser.getMethod("set" + methodName, (Class<?>) t);
method1.invoke(user, arg);
}
System.out.println(user);