Search code examples
javadozer

Dozer: Mapping of class with no default constructor


Lets say I want to map the following two classes:

public class A {

    String member;

    public void setMember(String member) { this.member = member }
    public String getMember() { return member }
}

public class B {

    String member;

    public B(String member) { this.member = member }

    public String getMember() { return member }
}

Now when I want Dozer to do the following conversion: dozerBeanMapper.map( a, B.class ); I get an error because of the missing default constructor of class B.

What's the best way to solve that problem? Use a custom converter?


Solution

  • If class B is not your API and you have no control over it and you intend to map member property anyway, you can get away with a custom bean factory that can perhaps pass a default value to the costructor:

    <mapping>
      <class-a>com.example.A</class-a>
      <class-b bean-factory="com.example.factories.BFactory">
        com.example.B
      </class-b>
    </mapping>
    

    Your factory will implement org.dozer.BeanFactory interface:

    public interface BeanFactory {
      public Object createBean(Object source, Class sourceClass, String targetBeanId);
    }