将不可变java对象转换为不可变对象(Immutable或Builder)

时间:2016-03-15 04:06:54

标签: dozer mapper orika

我想将一个不可变对象转换为另一个不可变对象。我用Google搜索,发现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;
}
}
}

我想互换地转换这两个结构。我不知道我可以创建自定义映射器来执行此任务。如果Dozzer / Orika可以轻松实现,请帮助我。

1 个答案:

答案 0 :(得分:0)

public class 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);
}

}