javadozer

Dozer map to a library class which does not have a default constructor


I'm trying to use Dozer to map to a target library class which has a field defined as an interface and I get an error :-

Caused by: java.lang.NoSuchMethodException: 
.<init>()
at java.base/java.lang.Class.getConstructor0(Class.java:3508) ~[na:na]
at java.base/java.lang.Class.getDeclaredConstructor(Class.java:2711) 

The source class has a matched field that has exactly the same structure as one of the implementations of that target interface. I have searched and cannot find any appropriate sultionsles. Would anybody be able to provide me with an example please. Thanks in advance.


Solution

  • Dozer does not implicitly know the concrete class to apply to the field defined as an interface. The mapping needs to include information about how to map that field.
    One option is to "copy by reference", which will take the instance of the field from the source and set it as the value for the field on the destination. The source and destination field instance must be compatible, in this case, the source field would need to be an implementation of the interface.
    Another option is to tell Dozer how to construct an instance of the interface. This can be done with a BeanFactory on the field mapping. The BeanFactory will be called by Dozer when mapping the field to get an instance of the destination field rather than trying to call a constructor on that class. A third option would be to create a custom converter for this field and specifying in the mapping to use the custom converter. The custom converter would implement both construction of the target field instance as well as population of that target field instance. Note that a mapper aware custom converter can call back into Dozer to map the fields of that target instance once it is constructed.