6

我知道那种类型的擦除,并且在定义映射时会阻止使用泛型,因为这个问题指出了如何用 Orika 映射泛型对象?. 但是Orika FAQ在“是否支持泛型”部分声称:

是的。Orika 通过一个特殊的 Type 类包括对泛型类型映射的特殊运行时支持,该类可用于定义模板化类型的确切类型元素。

理想情况下,如下所示应该可以工作(假设我们可以通过一些 Orika 功能在运行时以某种方式维护类参数):

     mapperFactory.classMap(Asset<T,K>.class, AssetDto<K>.class)
    .maybeSomeCustomization...
    .byDefault()
    .register();

我找不到有关Type<?>Orika 常见问题解答提到的类使用的任何示例。

4

2 回答 2

8

It is possible, you need to use the MapperFactory#classMap(Type<A>, Type<B>) API instead of MapperFactory#classMap(Class<A>, Class<B>).

You can find a lot of examples in Orika tests in the generics package.

To construct a Type instance you can use an in-place anonymous subclass of TypeBuilder:

Type<MyGenericClass<GenericParam1, GenericParam2>> type =
    new TypeBuilder<MyGenericClass<GenericParam1, GenericParam2>>() {}.build();

Note the brackets {} after the constructor which create the anonymous subclass. That way Orika can find out the actual MyGenericClass<GenericParam1, GenericParam2> type parameter using ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments().

于 2016-02-17T16:07:06.530 回答
0

您可以使用TypeBuilderAPI 保留泛型类型信息,以便 Orika 在执行映射时可以使用它。

请注意,Java 不允许我们在Class文字中指定类型参数。例如,我们不能写Asset<Book>.class. 此外,由于类型擦除,我们无法在运行时访问实际的类型参数。简而言之,原始类型 - 即Asset.class- 不要向 Orika 提供足够的信息。

因此,首先,我们必须使用以下方法创建泛型类型TypeBuilder

Type<Asset<Person>> sourceType = new TypeBuilder<Asset<Person>>() {}.build();
Type<AssetDto<Person>> targetType = new TypeBuilder<AssetDto<Person>>(){}.build();

然后在classMap调用中,我们必须使用这些类型:

factory.classMap(sourceType, targetType).byDefault().register();

最后,我们可以使用这些类型执行映射:

factory.getMapperFacade().map(asset, sourceType, targetType);

阅读以下文章,详细了解Orika 的泛型用法

于 2020-05-29T10:02:35.600 回答