Skip to content
Advertisement

ModelMapper: apply rule to all fields of type

I have a DTO with a lot of String fields (some are of other types).
When mapping objects into objects of another similar class, I need to apply a transformation to all fields of type String, in this case – trim().

So, I have:

JavaScript
JavaScript

What I’ve tried:

JavaScript

Is there a way to specify all String fields of a class at once, instead of having to list them?

Tried searching the modelmapper.org docs, but all I see is configuring fields one by one.

Any ideas?

Advertisement

Answer

You can use converters to specify transformations from one type to another. The source and target type can be the same. Use the addConverter<S,D>() method to add a general converter to the ModelMapper itself (rather than individually to a specific field). You can use it like this:

JavaScript

The output will be as expected:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement