Search code examples
javareflectionmappingpojo

What is a good way for getter to setter mapping from simple java objects (POJOs). Can is use reflection for it?


Hi i have two java objects, which are independent to each other, but share the same getter and setter methods. For example, I have an UserEntity and UserDTO object and I will map all getter values from the UserEntity to all setter of the UserDTO.

What is the best way of doing such kind of things? I prefer to do it with java reflection, but I also would like to now if there are some useful framework implementations outside.


Solution

  • There is a great mapper library called MapStruct which can used to map.

    Here an example for your UserEntity and UserDTO:

    @Mapper
    public interface UserMapper {
    
        UserMapper INSTANCE = Mappers.getMapper(UserMapper.class);
    
        @Mapping
        UserDTO userEntityToUserDTO(UserEntity user); 
    }
    
    UserDTO userDto = UserMapper.INSTANCE.userEntityToUserDTO(userEntity);
    

    It also supports conversion between compatible types and it's also possible to set custom mappings if fields aren't named the same. For example:

    @Mapping(source = "userName", target = "name")