Question

I am trying to understand when does Orika use converters to do the mapping versus direct casting.

I have the following mapping:

Class A {
  Map<String, Object> props;

}

Class B {
   String bStr;
   int bInt;

}

My mapping is defined as props['aStr'] => bStr and props['aInt'] => bInt

When I look at the generated code, I see that for the String case, it uses a converter and calls its convert method for the transformation:

destination.setBStr("" + ((ma.glasnost.orika.Converter)usedConverters[0]).convert(
        ((java.lang.Object) ((java.util.Map) source.getProps().get("aStr"),
        (ma.glasnost.orika.metadata.Type) usedTypes[0]))

But, for the integer case it directly casts it like this:

 destination.setBInt((java.lang.Integer)(java.lang.Object) ((java.util.Map)
     source.getProps().get("aInt")))

The above line of code ends up giving class cast exception.

For fixing this issue, I was thinking along the lines of using a custom converter but if the above line of code doesn't use the converter then that wont work.

Of course, I can always do this is in my custom mapper but just trying to understand how the code is generated for type conversion.

Thanks!!

Was it helpful?

Solution

In Orika there is two stages: config-time and runtime, as optimization Orika resolve all used converter in the config-time and cache them into each generated mapper so it will be accessible directly O(1) but in the config time it will try to find in a list O(n) of registered converters which one "canConvert" between two given types, canConvert is a method in Converter interface .

So this solution offer the best of the two worlds:

  • A very flexible way to register a converter with arbitrary conditions
  • An efficient resolution and conversion operation in the runtime.

Orika by default, leverage the existence of .toString in every object to offer implicit coercion to String for every Object. The problem here is that there is no Converter from Object to Integer.

Maybe this can be an issue of error reporting. Ideally Orika should report that an Object have to be converted to Integer and there is no appropriate converter registered.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top