Search code examples
mappingdozer

Dozer initialize property with empty string


I need to initialize with Dozer a String property on destination obect with empty string.

Imagine these objects:

SRC
public class Container {
            private String animalName;  
....
DEST
public class Animal {
    private String name;
    private String type;

I need to initialize from Container to Animal and to set type property to "" and not null:

The only way I found is to write a Custom Converter as follows:

public class InitializeStringConverter extends DozerConverter<Container, String>{

    public InitializeStringConverter() {
        super(Container.class, String.class);
    }

    @Override
    public Container convertFrom(String arg0, Container arg1) {
        return null;
    }

    @Override
    public String convertTo(Container arg0, String arg1) {
        return "";
    }
}

and having this mapping:

<mapping>
        <class-a>it.alten.sample.mapping.Container</class-a>
        <class-b>it.alten.sample.mapping.Animal</class-b>
        <field custom-converter="it.alten.sample.mapping.converter.InitializeStringConverter">
            <a>this</a>
            <b>type</b>
        </field>
        <!-- 
        <field>
            <a>animalName</a>
            <b>name</b>
        </field>
         -->
        <field>
            <a>animalType</a>
            <b>type</b>
        </field>
    </mapping>

Is there a more concise way to accomplish this task?

Kind regards Massimo


Solution

  • Dozer copies and converts values, it should not init fields in custom way as I think.

    My solution for your problem:

    1. Enable null mapping for class or field - docs
    2. Create setter, which init field with empty value instead of null, like:

      void setType(String type) {this.type = (type != null ? type : "");}

    I think, it more clear solution for your problem, because null control is functionality of setter and it's right.