Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it actually possible to use generics when defining mappings in Orika?

Tags:

java

orika

I know about that type erasure and would prevent to use generics when defining mappings, as this question points out how to map generics objects with Orika?. But Orika FAQ, on the Are generics supported section, claims:

Yes. Orika includes special runtime support for the mapping of generic types via a special Type class which can be used to define the exact type elements of a templated type.

Ideally something like the following should work (supposing we can somehow maintain the class parameters at runtime through some Orika functionality):

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

I was not able to find any example about the Type<?> class usage the Orika FAQ mentions.

like image 484
David Fernandez Avatar asked Feb 17 '16 14:02

David Fernandez


1 Answers

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().

like image 65
Adam Michalik Avatar answered Sep 17 '22 23:09

Adam Michalik