我正在使用 Orika 1.4.5,我想让我的 BidirectionalConverter 进行映射
PaginatedResponse<T> to PaginatedResponse<S>
,反之亦然。
PaginatedResponse 类如下:
public class PaginatedResponse<T> {
private List<T> items;
private List<Sorting> orderBy;
private PagingResponse paging;
public PaginatedResponse(List<T> items, List<Sorting> orderBy, PagingResponse paging) {
this.items = items;
this.orderBy = orderBy;
this.paging = paging;
}
// Getters
}
所以我希望我的 PaginatedResponseCovnerter 接受转换所在的所有地图调用PaginatedResponse<Something> object1 to PaginatedResponse<OtherSomething> object2
,并且我希望 object1 和 object2 具有相同的 orderBy 和 paging 属性。所以我尝试这样做:
public class PaginatedResponseConverter<T, S>
extends BidirectionalConverter<PaginatedResponse<T>, PaginatedResponse<S>>
implements MapperAware {
private MapperFacade mapper;
private T clazz1;
private S clazz2;
public PaginatedResponseConverter(T clazz1, S clazz2) {
this.clazz1 = clazz1;
this.clazz2 = clazz2;
}
@Override
public void setMapper(Mapper mapper) {
this.mapper = (MapperFacade) mapper;
}
@Override
@SuppressWarnings("unchecked")
public PaginatedResponse<S> convertTo(PaginatedResponse<T> source, Type<PaginatedResponse<S>> destinationType) {
System.out.println("ConverTo");
PagingResponse paging = source.getPaging();
List<Sorting> sortings = source.getOrderBy();
List<S> items = (List<S>) this.mapper.mapAsList(source.getItems(), this.clazz2.getClass());
return new PaginatedResponse<S>(items, sortings, paging);
}
@Override
@SuppressWarnings("unchecked")
public PaginatedResponse<T> convertFrom(PaginatedResponse<S> source, Type<PaginatedResponse<T>> destinationType) {
// The same upside down
}
}
但问题是我必须用泛型参数注册这个自定义转换器,而这些并不总是相同的。我希望如果我尝试转换 fromPaginatedResponse<SomeClass1> to PaginatedResponse<SomeClass2>
是一样的,PaginatedResponse<AnotherClass1> to PaginatedResponse<AnotherClass2>
顺便说一句,我不能这样做:
converterFactory.registerConverter(new PaginatedResponseConverter<Object, Object>(Object.class, Object.class));
因为通过这种方式,所有 PaginatedResponse 调用都会进入 PaginatedResponseConverter 但我不知道类的真实类型,所以当它进入 converTo 或 convertFrom 方法时,需要通用参数的确切类来执行 mapAsList() 方法
你能帮我解决这个问题吗?