2014-01-28 22 views
0

我有以下目標類:如何用推土機實例化子類?

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但與對象,但與員工對象。我真的不知道如何實現這一點。如何告訴Dozer實例化一個子類?

這種映射給對象:

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

可以這樣做略低modyfing這種映射?

回答

0

嘗試改變Person類領域的保護,使他們可以繼承

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

變化從PersonContainer到(你希望它是什麼)

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

希望它可以幫助

+0

從PersonContainer可惜的改變,以EmployeeContainer是不一樣。這是更復雜問題的簡單例子。這裏主要的是實例化子類Employee並將其放入超類字段中。 – Hubert

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

是的,這工作正常。只有一件事:你知道如何爲Employee.position設置價值嗎? person.position不起作用,因爲字段PersonContainer.person的類型是Person。 – Hubert

+0

您可以在字段映射上使用自定義轉換器進行類似的操作。 field1field2如果目標對象是員工,那麼CustomConverter會解決問題,如果是的話,請將其轉換並設置值。 http://dozer.sourceforge.net/documentation/customconverter.html – M21B8