orika-mapper/orika

Workaround for multiple CustomConverters with the same (could be anonymous) classes.

sparecycles opened this issue · 0 comments

The fix is to flush the converter into the lookup cache immediately after registration... as I found with the following code:

 void registerConverter(MapperFactory factory, Type<A> aType, Type<B> bType, ...) {
 	CustomConverter converter = new CustomConverter() { ... };

	ConverterFactory converterFactory = factory.getConverterFactory();

	converterFactory.registerConverter(converter);

	// flush converter into cache
	converterFactory.getConverter(aType, bType);
	converterFactory.getConverter(bType, aType); // only because my converter is bidirectional 
}

Note: it will be necessary to do the cache fill externally to registerConverter(...) since the pairs of types that getConverter() resolves to the new converter are dependent on the result of the canConvert() method.


Looking into this more, it seems it's a workaround for the following equals and hashCode implementation in CustomConverter which is based on the class. (remove this code please?)

public boolean equals(Object other) {
return other != null && getClass().equals(other.getClass());
}
public int hashCode() {
return getClass().hashCode();
}

...the issue is that anonymous classes all have the same "class" object but different bound variables, so the processing of the converters in the DefaultConverterFactory through a LinkedHashSet will end up overwriting all but the last one registered!

Set<Converter<Object, Object>> orderedConverters = new LinkedHashSet<>();
for (Converter<Object, Object> converter : converters) {
converter.setMapperFacade(mapperFacade);
orderedConverters.add(converter);
}
converters = orderedConverters;

It looks like this was first reported in 2017. Let's get this fixed?