Search code examples
javadozer

How to instantiate a subclass with Dozer?


I have following target classes:

public class Person {
    private String firstName;
    private String lastName;
    ...
}

public class Employee extends Person {
    private String postion;
    ...
}

public class PersonContainer {
   private Person person;
   ...
}

And this is my source:

public class Form {
    private String firstNameEmployee;
    private String lastNameEmployee;
    private String positionEmployee;
    ...
}


GOAL

I would like to get object PersonContainer but not with Person object but with Employee object. I really have no idea how to achieve that. How to tell Dozer to instantiate a subclass?

This mapping gives Person object:

 <mapping>
    <class-a>hl.test.dozer03.form.Form</class-a>
    <class-b>hl.test.dozer03.result.PersonContainer</class-b>


    <field>
        <a>firstNameEmployee</a>
        <b>person.firstName</b>
    </field>

    <field>
        <a>lastNameEmployee</a>
        <b>person.lastName</b>
    </field>

 </mapping>


Can this be done by slightly modifying this mapping?


Solution

  • You need to use a custom-createMethod. http://dozer.sourceforge.net/documentation/customCreateMethod.html

    Something like this:

    <mapping>
      <class-a>hl.test.dozer03.form.Form</class-a>
      <class-b create- method="PersonContainerFactory.createPersonContainer">hl.test.dozer03.result.PersonContainer</class-b>
    
    
      <field>
        <a>firstNameEmployee</a>
        <b>person.firstName</b>
      </field>
    
      <field>
        <a>lastNameEmployee</a>
        <b>person.lastName</b>
      </field>
    
    </mapping>
    

    With the java class:

    public class PersonContainerFactory {
    
      public static PersonContainer createPersonContainer(){
          PersonContainer cont = new PersonContainer();
          cont.setPerson(new Employee());
          return classA;
      }
    }