public class Main {
public static void main(String[] args) {
AEntity aEntity = new AEntity();
BEntity bEntity = new BEntity();
// 检查并赋值属性
checkAndAssign(aEntity, bEntity);
// 输出结果
System.out.println(aEntity);
}
private static void checkAndAssign(AEntity aEntity, BEntity bEntity) {
// 获取 AEntity 和 BEntity 的 Class 对象
Class<?> aClass = aEntity.getClass();
Class<?> bClass = bEntity.getClass();
// 获取所有字段
Field[] aFields = aClass.getDeclaredFields();
Field[] bFields = bClass.getDeclaredFields();
// 遍历字段
for (Field aField : aFields) {
try {
// 设置字段可访问
aField.setAccessible(true);
// 获取字段值
Object value = aField.get(aEntity);
// 如果字段值为空,则从 BEntity 中获取相同字段的值
if (value == null) {
for (Field bField : bFields) {
if (bField.getName().equals(aField.getName())) {
bField.setAccessible(true);
Object bValue = bField.get(bEntity);
// 将 BEntity 的值赋给 AEntity
aField.set(aEntity, bValue);
}
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}