首页 > 解决方案 > 如何映射两个类中的所有可用字段(无继承)

问题描述

假设我有两个 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,而是自动使用

标签: javamapping

解决方案


你可以使用反射:

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

推荐阅读