is there a way to extract Mapstruct mapping?

Viewed 588

Let says I have a basic case where I map an object to an other, I need to declare the mapping in the Mapper class.

For validation I may want to remember the original field name and his corresponding mapping.

Is there a way to do it with mapstruct without having to do a mapping "manually"

here is an example of what I would expect.

public class PersonDemo {

    public static void main(String[] args) {
        final PersonMapper mapper = Mappers.getMapper(PersonMapper.class);
        Person person = mapper
            .toPerson(new PersonDto()
                .setFirstName("John")
                .setName("Doe"));

        System.out.println(person);

        System.out.println("Expected " + toPersonDesc("firstName") + " to be firstName");
        System.out.println("Expected " + toPersonDesc("name") + " to be lastName");
    }

    @Mapper
    public interface PersonMapper {
        @Mapping(target = "lastName", source = "name")
        Person toPerson(PersonDto dto);

    }

    //expected method. to be generated somehow from the mapping.
    static String toPersonDesc(String fieldName) {
        switch (fieldName) {
            case "name": return "lastName";
            case "firstName": return "firstName";
        }
        return null;
    }

    @Data
    @Accessors(chain = true)
    public static class Person {

        private String lastName;
        private String firstName;
    }

    @Data
    @Accessors(chain = true)
    public static class PersonDto {

        private String name;
        private String firstName;
    }
}

1 Answers

It's impossible with Mapstruct. There's another question similar to yours: How to provide MapStruct Mapping annotation mapping meta data at runtime. The answer there describes "some" approach to the problem, but it's very limited - it simply scrapes the information from the @Mapping annotations (no support for implicit mappings).

It would be quite useful to have this though - you should propose this feature to the Mapstruct team.

Related