简体   繁体   中英

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?

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);
}

From Dozer FAQ :

Some of my data objects don't have public constructors. Does Dozer support this use case?

Yes. When creating a new instance of the destination object if a public no-arg constructor is not found, Dozer will auto detect a private constructor and use that. If the data object does not have a private constructor, you can specify a custom BeanFactory for creating new instances of the destination object.

Here is a documentation of Custom Bean Factories

I ran into this issue while trying to map a java.util.Locale . To solve my problem I did as follows :

I created a class called LocaleMapper which would match dumb LocaleToLocaleConversion

public class LocaleMapper extends DozerConverter<Locale, Locale> {
    public LocaleMapper() {
        super(Locale.class, Locale.class);
    }

    @Override
    public Locale convertTo(Locale localeA, Locale localeB) {
        return localeA;
    }

    @Override
    public Locale convertFrom(Locale localeA, Locale localeB) {
        return localeA;
    }
}

Then I modified the mapping xml of the project :

<converter type="LocaleMapper">
            <class-a>java.util.Locale</class-a>
            <class-b>java.util.Locale</class-b>
 </converter>

Now I can add Locale objects to my classes that are mapped with Dozer. My Dozer knowledge is somewhat limited, so I can't explain the indepth details of how it works underneath the hood, but it worked for my project.

您可以为B创建默认构造函数,也可以使用自定义BeanFactory ,以便Dozer可以创建所需的实例。

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