1

我想将一个不可变对象转换为另一个不可变对象。我搜索了一下,发现 Dozzer 和 Orika 主要用于对象映射。

我尝试使用 Dozzer,但似乎它不适用于使用构建器模式创建的对象。

Example:
//Source Object
public class EmployeeDTO{
private String id;
private String name;

private void setName(String name){this.name=name;}
private void setId(String id){this.id=id;}

public static class Builder{
public String id;
public String name;
public Builder setName(String name){this.name=name;}
public Builder setId(String id){this.id=id;}

public EmployeeDTO build(){
  EmployeeDTO employeeDTO = new EmployeeDTO();
employeeDTO.setName(this.name);
employeeDTO.setId(this.id);
return employeeDTO;
}
}
}

//Target Object
public class Employee{
private String id;
private String name;

private void setName(String name){this.name=name;}
private void setId(String id){this.id=id;}

public static class Builder{
public String id;
public String name;
public Builder setName(String name){this.name=name;}
public Builder setId(String id){this.id=id;}

public Employee build(){
  Employee employee = new Employee();
employee.setName(this.name);
employee.setId(this.id);
return employee;
}
}
}

我想互换地转换这两种结构。我几乎不知道我可以创建 custommapper 来执行此任务。如果 Dozzer/Orika 可以简单地使用,请帮助我。

4

1 回答 1

0

公共类 SourceObjectClass 实现 T{

private final String name;

private final int id;

public sourceObjectClass(final String name, final int id){

    this.name = name;
    this.id = id;
}

public String getName(){

    return name;
}

public String getId(){

    return id;
}

}

//目标对象

公共类 DestinationObjectClass 实现 T{

private final String name;

private final int id;


public sourceObjectClass(final String name, final int id){

    this.name = name;
    this.id = id;
}

public String getName(){

    return name;
}

public String getId(){

    return id;
}

}

//转换器

//转换器

公共类 MyConverter{

public static T convert(SourceObjectClass sourceObject, Class<T> destinationClass){

    Class definition = Class.forName(destinationClass);

    return definition.newInstance(sourceObject.getName(),sourceObject.getId());
}

}

公共类 MyTestClass{

public static void main(String args[]){

    //Create an immutable object
    SourceClasssObject sourceObject = new SourceClassObject("Guest",100);

    //convert the above object into another immutable Object
    final DestinationObjectClass destination = MyConverter.convert(sourceObject,DestinationObjectClass.class);
}

}

于 2016-03-16T19:58:38.720 回答