Bulldozer 5.3.2. Programmatically install custom converters?

How to programmatically install a custom converter for a bulldozer? The following code does not work:

Custom Converter Implementation:

class ConverterImpl extends DozerConverter<A, B> { ConverterImpl() { super(A.class, B.class); } @Override public B convertTo(A source, B destination) { return destination; } @Override public A convertFrom(B source, A destination) { return destination; } } 

Test code:

 DozerBeanMapper mapper = new DozerBeanMapper(); mapper.setCustomConverters(Collections.<CustomConverter>singletonList(new ConverterImpl())); A a = new A(); B b = mapper.map(a, A.class); 

After executing the code above, the custom converter will not be called. What's wrong?

+6
source share
2 answers

It looks like you should actually add a specific mapping, and unfortunately, you can only specify field level converters, not class level converters, using the software API. Therefore, if you transfer classes A and B to container classes, you can specify a mapping for fields A and B.

For example, the following verbose code works as expected:

 public class DozerMap { public static class ContainerA { private A a; public A getA() { return a; } public void setA(A a) { this.a = a; } } public static class ContainerB { private B b; public B getB() { return b; } public void setB(B b) { this.b = b; } } private static class A { }; private static class B { }; static class ConverterImpl extends DozerConverter<A, B> { ConverterImpl() { super(A.class, B.class); } @Override public B convertTo(A source, B destination) { Logger.getAnonymousLogger().info("Invoked"); return destination; } @Override public A convertFrom(B source, A destination) { Logger.getAnonymousLogger().info("Invoked"); return destination; } } public static void main(String[] args) { DozerBeanMapper mapper = new DozerBeanMapper(); mapper.setCustomConverters(Collections.<CustomConverter> singletonList(new ConverterImpl())); BeanMappingBuilder foo = new BeanMappingBuilder() { @Override protected void configure() { mapping(ContainerA.class, ContainerB.class).fields("a", "b", FieldsMappingOptions.customConverter(ConverterImpl.class)); } }; mapper.setMappings(Collections.singletonList(foo)); ContainerA containerA = new ContainerA(); containerA.a = new A(); ContainerB containerB = mapper.map(containerA, ContainerB.class); } } 
+4
source

Why do you want to install it programmatically? I mean, do you have any specific needs? Otherwise, mapping through an XML file works fine.

If you want to do this more programmatically, and through some xml configuration files, open Orika .

It has good API support.

+1
source

Source: https://habr.com/ru/post/915642/


All Articles