Search code examples
javadozer

how to generate class instances of attributes on demand?


I'm evaluating the dozer framework right. I was wondering whether it is possible to handle the following use case:

the classes:

public ClassA {

   private Set<ItemA> aItems;
}

public ClassB {

   private ClassC cInstance;
}

public ClassC {

   private List<ItemB> bItems;
}

the dozer mapping:

<mapping>
   <class-a>ClassA</class-a>
   <class-b>ClassB</class-b>
   <field>
      <a>aItems</a>
      <b>cInstance.bItems</b>
   </field>
 </mapping>

From my testings so far, this doesn't seem to work. I was especially wondering how should I tell dozer that it should generate an instance of ClassB and ClassC on demand? Especially do I need a specific dozer mapping for ClassB, which only exists as "intermediate" class in my destination model?

PS: If it helps, my destination model consists of JAXB classes

PPS: I also tried to modify the setter method for cInstance that if it is null it should generate a new instance of ClassC - unfortunately, without any luck. Furthermore, I do not want to modify the setter method in that way (however, maybe I can outsource this to a Factory class that will be utilised for the mapping)


Solution

  • So it looks like that the final solution is rather simple, since my destination classes are JAXB classes, I could simply utilise the default factory for JAXB classes (org.dozer.factory.JAXBBeanFactory). The tipping point probably is that the deep mapping destination field should be accessed directly ('is-accessible="true"'). However, I also created a further direct mapping from ClassA.aitems to ClassC.cItems (but I'm not 100% sure whether this will be utilised for the described ClassA to ClassB mapping). Anyway, finally I found a rather simple and intuitive solution with less/no additional factory coding.