1)创建类
class Person {
public Person(){}
public Person(int id, String name) {
this.id = id;
this.name = name;
}
//主键
private int id;
//姓名
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Student extends Person {
public Student(){}
public Student(int id, String name, String no, String school) {
super(id, name);
this.no = no;
this.school = school;
}
//学号
private String no;
//学校
private String school;
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
}
2)父对象赋值给子对象方法(对象A赋值给对象B)
public static <TParent, TChild> TChild AutoCopy(TParent parent, Class<TChild> childClass) {
TChild child = null;
try {
child = childClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
if (child != null) {
CopyFields(parent, child);
}
return child;
}
public static void CopyFields(Object source, Object target) {
Class<?> sourceClass = source.getClass();
Class<?> targetClass = target.getClass();
Field[] sourceFields = GetAllFields(sourceClass);
Field[] targetFields = GetAllFields(targetClass);
for (Field sourceField : sourceFields) {
sourceField.setAccessible(true);
for (Field targetField : targetFields) {
targetField.setAccessible(true);
if (sourceField.getName().equals(targetField.getName()) && sourceField.getType() == targetField.getType()) {
try {
Object value = sourceField.get(source);
targetField.set(target, value);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
}
public static Field[] GetAllFields(Class<?> clazz) {
Field[] fields = clazz.getDeclaredFields();
Class<?> superClass = clazz.getSuperclass();
if (superClass != null) {
Field[] parentFields = GetAllFields(superClass);
Field[] combinedFields = new Field[fields.length + parentFields.length];
System.arraycopy(fields, 0, combinedFields, 0, fields.length);
System.arraycopy(parentFields, 0, combinedFields, fields.length, parentFields.length);
fields = combinedFields;
}
return fields;
}
3)调用
// 父对象转化成子对象
// 这边实现的是对象A赋值给对象B
// 原理是循环对象属性,如果属性名称相同赋值
Person parent1 = new Person(1, "学生1");
Student student = AutoCopy(parent1, Student.class);
student.setNo("s001");
student.setSchool("学校1");
// 将子对象转换为父对象
// 这边实现的是对象A赋值给对象B
// 原理是循环对象属性,如果属性名称相同赋值
Person parnet2 = AutoCopy(student, Person.class);