I'd like to do something like:
ArrayList<CustomObject> objects = new ArrayList<CustomObject>();
...
DozerBeanMapper MAPPER = new DozerBeanMapper();
...
ArrayList<NewObject> newObjects = MAPPER.map(objects, ...);
Assuming:
<mapping>
<class-a>com.me.CustomObject</class-a>
<class-b>com.me.NewObject</class-b>
<field>
<a>id</a>
<b>id2</b>
</field>
</mapping>
I tried :
ArrayList<NewObject> holder = new ArrayList<NewObject>();
MAPPER.map(objects, holder);
but the holder object is empty. I also played with changing the second argument without any luck...
I have done it using Java 8 and dozer 5.5. You don't need any XML files for mapping. You can do it in Java.
You don't need any additional mapping for lists, only thing you need is
. See the sample bean config below.
Spring configuration class
//Answer class and AnswerDTO classes have same attributes
//QuestionAndAnswerDTO class has a list of Answers
//LET the QuestionAndAnswer class has similar fields as QuestionAndAnswerDTO
//Then to use the mapper in your code, autowire it
Hope this will help someone follow the Java approach instead of XML.
you can do it like this :
}
and use it :
Not really an improvement, more like a syntactic sugar that can be achieved thanks to Guava (and most likely similar thing is possible with Apache Commons):
This can also be turned into a generic function - as suggested in other answers.
You can implement your own mapper class which will extend dozer mapper. Example: Create a interface that adds additional method to dozer mapper:
Next step: Write your own Mapper class by implementing above interface.
add below method to your implementation class:
Hope this helps
What is happening is that you are getting bitten by type erasure. At runtime, java only sees an
ArrayList.class
. The type ofCustomObject
andNewObject
aren't there, so Dozer is attempting to map ajava.util.ArrayList
, not yourCustomObject
toNewObject
.What should work (totally untested):
For that use case I once wrote a little helper class:
You then would call dozer in the following manner:
Only drawback: You get a "unchecked" warning on
mapper.map(...)
because of Dozers Mapper interface not handling generic types.