Search code examples
dozer

Dozer Mapping with custom argument


I would need to map classA fields to classB fields along with localization i.e ClassA field values needs to be converted to localized value before it mapped to classB field. Locale should be passed as an argument to mapper in order get the localized value. Is there any option to pass runtime argument to mapper along with Source and Target classes? Thanks.


Solution

  • Yes, you can do this. Let's get this example from Dozer docs

    BeanMappingBuilder builder = new BeanMappingBuilder() {
          protected void configure() {
            mapping(Bean.class, Bean.class,
                    TypeMappingOptions.oneWay(),
                    mapId("A"),
                    mapNull(true)
            )
                    .exclude("excluded")
                    .fields("src", "dest",
                            copyByReference(),
                            collectionStrategy(true, 
                                RelationshipType.NON_CUMULATIVE),
                            hintA(String.class),
                            hintB(Integer.class),
                            FieldsMappingOptions.oneWay(),
                            useMapId("A"),
                            customConverterId("id")
                    )
                    .fields("src", "dest",
                        customConverter("org.dozer.CustomConverter")
                    );
          }
        };
    

    Here we can find an example of dynamically configuration definition. Take a look at this part

    customConverter("org.dozer.CustomConverter")
    

    Here you can define a custom converter using this method

    FieldsMappingOption customConverter(final String type)
    

    But it has another version

    customConverter(final Class<? extends CustomConverter> type, final String parameter)
    

    And that's your case. You can write smth like

    customConverter(com.yourproject.TranslatorConverter.class, "en")
    

    in your dynamic code base config to define a parameter for you converter. How to write an implementation of CustumConverter which apply a parameter - take a look here