我有两个不可变的 bean类,我使用Orika映射将值从一个复制到另一个。
但是,当我尝试通过Orika映射复制unmodifiableList
时,它会因为抛出以下异常而失败:
java.lang.UnsupportedOperationException
at ma.glasnost.orika.ExceptionUtility.newMappingException(ExceptionUtility.java:55)
at ma.glasnost.orika.impl.MapperFacadeImpl.map(MapperFacadeImpl.java:681)
at ma.glasnost.orika.impl.MapperFacadeImpl.map(MapperFacadeImpl.java:650)
at com.myproject.OrikaTest.testEmployeeMapping
我提供了以下代码,您可以使用该代码复制相同的问题:
EmployeeDto class:
public final class EmployeeDto {
private final int id;
private final String name;
private final List<String> previousGrades;
public EmployeeDto(int id, String name, List<String> previousGrades) {
this.id = id;//validations removed
this.name = name;//validations removed
//Commented unmodifiableList as it does not work
//this.previousGrades = Collections.unmodifiableList(previousGrades);
this.previousGrades = previousGrades;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public List<String> getPreviousGrades() {
//tried like this, even this does not work
return Collections.unmodifiableList(previousGrades);
}
}
员工类:
public final class Employee {
//ditto AS EmployeeDto
}
OrikaTest课程:
public class OrikaTest {
private static final MapperFactory mapperFactory =
new DefaultMapperFactory.Builder().build();
private static final MapperFacade mapperFacade =
mapperFactory.getMapperFacade();
@Test
public void testEmployeeMapping() {
List<String> employeeGrades = Arrays.asList("A", "B");
Employee employee = new Employee(1234, "John", employeeGrades);
EmployeeDto employeeDto = mapperFacade.map(employee, EmployeeDto.class);
//tests using assertEquals
Assert.assertEquals(employeeGrades, employeeDto.getPreviousGrades());
}
}
我可以找到关于这个主题的链接here,但由于没有正确解释替代方案,因此不太清楚。
那么,您可以帮助解决如何通过Orika映射复制unmodifiableList
的示例或任何解决方法吗?
答案 0 :(得分:0)
如果案例是Orika必须能够改变映射对象的列表组件,那么以下可能是一个解决方法:
向对象添加freeze
方法。创建对象时,它们处于可变状态。调用freeze
后,不再可能改变对象。
可以这样实现:
public final class EmployeeDto {
private final int id;
private final String name;
private List<String> previousGrades;
public EmployeeDto(int id, String name, List<String> previousGrades) {
this.id = id;//validations removed
this.name = name;//validations removed
this.previousGrades = previousGrades;
}
public void freeze() {
previousGrades = Collections.unmodifiableList(previousGrades)
}
public List<String> getPreviousGrades() {
return previousGrades;
}
}