Short answer
There is no native way in plain Java to convert an object of type A to an object of type B without having to copy the fields one by one.
Longer answer
Why is that?
There is no such thing as similar fields in Java. The Java language by design does not support duck typing. Thus said you cannot treat a two fields fields as similar / same by their names.
How can I get it done?
There are different approaches:
This is a boring but runtime performant approach.
Inheritance and polymorphism
Not really a mapping approach, but rather treating the objects as similar by their common interfaceand/orparent class`.
- Serialization and deserialization to/from
String
If the two types have fields with same names and types they can be mapped from one to another by serialization/deserialization (e.g. GSON). This is not the best solution, but may do the good job in some rare cases.
- Using
reflection and reflection-based libraries:
Reflection is another way of achieving the same goal, but with huge trade-offs.
This approach is not so different from the one above, but it allows to map fields with different names. Even though the approach is widely used (e.g. in Dozer) it is not very performant. The reflective operations may take significant time.
There is another approach. As opposed to using reflection at runtime, the code generators (like MapStruct) do the similar thing at compile time. Thus there is no runtime overhead as compared to manual mapping. Actually, the generated code looks quiet the same as the manually written one.
How to choose one for my project?
There is a bunch of different tools for mapping POJO types between each other.
Before choosing one of them for using in your project I'd suggest considering the following criteria:
- Is the particular case worth adding external dependency?
- Is it easy to read?
- Is it easy to modify the classes without breaking the code?
- Is it performant at runtime?
- etc...
Subjective opinion:
I personally like using MapStruct. It generates the methods for mapping at compile time, so there is no runtime reflective stuff causing overhead. You can map the objects at almost zero cost.