简体   繁体   中英

Dozer mapping for objects without setters

public class ParentOne {

    private List<ChildOne> child;

    public List<ChildOne> getChild() {
        if (child == null) {
            child = new ArrayList<ChildOne>();
        }
        return child;
    }
}

public class ParentTwo {

    private List<ChildTwo> child;

    public List<ChildTwo> getChild() {
        if (child == null) {
            child = new ArrayList<ChildTwo>();
        }
        return child;
    }
}

DOZER Mapping

<mapping>
    <class-a>ParentOne</class-a>
    <class-b>ParentTwo</class-b>
    <field>
        <a is-accessible="true">child</a>
        <b is-accessible="true">child</b>
    </field>
</mapping>

public class Client {

    public static void main(String[] args) {
        ParentOne parentOne = new ParentOne();
        parentOne.getChild().add(new ChildOne());
        parentOne.getChild().add(new ChildOne());

        ParentTwo parentTwo = dozerBeanMapper.map(parentOne, ParentTwo.class);
    }
}

The Parent class doesn't contain the setters for the list. hence I made the dozer mapping in such a way to access the fields directly. The mapping happens fine but the problem is after mapping the parentTwo instance contains child of type ChildOne, it is supposed to be ChildTwo.

Did I miss anything?

Add hints (see here for more info).

<mapping>
    <class-a>ParentOne</class-a>
    <class-b>ParentTwo</class-b>
    <field>
        <a is-accessible="true">child</a>
        <b is-accessible="true">child</b>
        <a-hint>ChildOne</a-hint>
        <b-hint>ChildTwo</b-hint>
    </field>
</mapping>

You might need to use the fully qualified names of the classes rather than just ChildOne and ChildTwo , but other than that, it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM