Java – How to pass `this` to Dozer field mapping

dozerjava

In my app I have Dozer mapping which looks like this:

<mapping>
    <class-a>java.util.HashMap</class-a>
    <class-b>org.mycompany.TargetClass</class-b>
    <field custom-converter="org.example.MyConverter">
        <a>this</a>
        <b>anotherField</b>
    </field>
</mapping>

MyConverter is an instance of ConfigurableCustomConverter:

public class MyConverter implements ConfigurableCustomConverter {

    private String parameter;

    @Override
    public Object convert(
            Object existingDestinationFieldValue,
            Object sourceFieldValue,
            Class<?> destinationClass,
            Class<?> sourceClass) {
        // sourceClass is always java.lang.Object and
        // sourceFieldValue is always null!!!
    }

    @Override
    public void setParameter(String parameter) {
        this.parameter = parameter;
    }
}

Why things noted in in-source comment happen?

Best Solution

You need to tell dozer which key of the Map should be mapped to b.anotherField, with something like

<field custom-converter="org.example.MyConverter">
    <a key="foobar">this</a>
    <b>anotherField</b>
</field>

See http://dozer.sourceforge.net/documentation/mapbackedproperty.html#Mapping_Class_Level_Properties_to_a_java.util.Map_or_a_Custom_Map_with_unique_GetSet_methods