如何映射两个类中的所有可用字段(没有继承)

问题描述 投票:0回答:1

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

java mapping
1个回答
0
投票

你可以使用反射:

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
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.