我有以下目标类:
public class Person {
private String firstName;
private String lastName;
...
}
public class Employee extends Person {
private String postion;
...
}
public class PersonContainer {
private Person person;
...
}
这是我的来源:
public class Form {
private String firstNameEmployee;
private String lastNameEmployee;
private String positionEmployee;
...
}
我想获取对象 PersonContainer ,但不能使用 Person 对象,而是使用 Employee 对象。我真的不知道如何实现这一目标。如何告诉Dozer实例化一个子类?
此映射提供 Person 对象:
<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>
可以通过稍微修改此映射来完成吗?
答案 0 :(得分:1)
您需要使用custom-createMethod。 http://dozer.sourceforge.net/documentation/customCreateMethod.html
这样的事情:
<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>
使用java类:
public class PersonContainerFactory {
public static PersonContainer createPersonContainer(){
PersonContainer cont = new PersonContainer();
cont.setPerson(new Employee());
return classA;
}
}
答案 1 :(得分:0)
尝试将Person类字段更改为protected,以便可以继承它们
public class Person {
protected String firstName;
protected String lastName;
...
}
从PersonContainer更改为(你想要的是什么)
public class EmployeeContainer {
private Employee employee;
...
}
希望有所帮助