Frage

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?

War es hilfreich?

Lösung

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

Andere Tipps

Try changing the Person class fields to protected so they can be inherited

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

Change from PersonContainer to (what it is you want)

public class EmployeeContainer {
   private Employee employee;
   ...
}

Hope it helps

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top