java - 如何映射两个类中的所有可用字段(无继承)
问题描述
假设我有两个 A 类和 B 类,
A类有很多很多领域。B类有一些字段,所有字段都出现在A类中。
是否可以自动将可用字段从对象 A 映射到对象 B?
@编辑
class A {
private int field1;
private int field2;
private int field3;
private int field4;
private int field5;
private int field6;
private int field7;
// getters, setters
}
class B {
private int field2;
private int field6;
// getters, setters
}
当我反对 A 和 B 时,我想从 A 获取字段并放入 B。但我不想使用 getter/setter,而是自动使用
解决方案
你可以使用反射:
A a = new A();
B b = new B();
a.field1 = 1;
a.field2 = 3;
for (Field aField : a.getClass().getDeclaredFields()) {
try {
Field bCounterpart = b.getClass().getDeclaredField(aField.getName());
if (bCounterpart.getType().equals(aField.getType())) { // Doesn't work well with autoboxing etc. The types have to explictly match
bCounterpart.setAccessible(true); // Only for private fields
aField.setAccessible(true); // Only for private fields
bCounterpart.set(b, aField.get(a));
}
} catch (NoSuchFieldException e) {
// B doesn't have the field
}
}
System.out.println(b.field2); // 3
System.out.println(b.field6); // 0
推荐阅读
- spring-boot - 在 Spring Boot 中创建 google Oauth2 自定义错误页面
- javascript - 使用机车滚动滚动时图像或内容消失
- react-native - 如何在亚马逊移动分析上进行个人用户跟踪?
- json - 解析 JSON 以角度显示数据
- opencv - 两个版本的 OpenCV 以及如何消除一个
- reactjs - 反应钩子。无法读取嵌套列表的属性“地图”
- wordpress - 如何在推荐页面上进行分页?
- java - 如何在卡内制作具有可扩展功能的 Recylerview(使用滚动位置触发)
- python - 有什么方法可以流畅地接收音频并将其发送到后端
- sql - 如何在Oracle中使用条件计算多列的总和