有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何用Dozer实例化子类?

我有以下目标课程:

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实例化一个子类

此映射提供了个人对象:

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


这可以通过稍微修改此映射来实现吗


共 (2) 个答案

  1. # 1 楼答案

    您需要使用自定义的createMethodhttp://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;
      }
    }
    
  2. # 2 楼答案

    尝试将Person类字段更改为protected,以便可以继承它们

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

    从PersonContainer更改为(您想要的是什么)

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

    希望能有帮助