3

Am seeing behaviour I can't explain with ModelMapper whilst trying to map a boolean to char.

(I have checked, and the problem isn't Lombok related).

@Data @NoArgsConstructor @AllArgsConstructor
public class Entity { private boolean instance; }
@Data @NoArgsConstructor @AllArgsConstructor
public class Item { private char instance; }

public final class ModelMapperTest
{
    private final ModelMapper modelMapper = new ModelMapper();

    @Before
    public void before()
    {
        modelMapper.addMappings(new PropertyMap<Entity, Item>()
        {
            protected void configure()
            {
                map().setInstance(source.isInstance() ? 'Y' : 'N');
            }
        });
    }

    @Test
    public void map()
    {
        for (final Item item : map(new ArrayList<Entity>()
        {
            {
                this.add(new Entity(true));
                this.add(new Entity(false));
            }
        }))
        {
            System.out.println(item);
        }
    }

    public List<Item> map(final List<Entity> entities)
    {
        return modelMapper.map(entities, new TypeToken<List<Item>>(){}.getType());
    }
}

Which produces characters 't' and 'f' not 'Y' and 'N' as I'd intended.

Item(instance=t)

Item(instance=f)

Anyone know how the ModelMapper configuration should look?

Community
  • 1
  • 1
Andrew Eells
  • 735
  • 12
  • 30

1 Answers1

1

I think you need to create a converter to map a boolean to char like this:

Converter<boolean, char> toChar = new AbstractConverter<boolean, char>() {
  protected char convert(boolean source) {
    return source ? 'Y' : 'N;
  }
}; 

Then your ProperyMap should use this converter to map it as below:

    @Before
    public void before()
    {
        modelMapper.addMappings(new PropertyMap<Entity, Item>()
        {
            protected void configure()
            {
                using(toChar).map().setIsInstance(source.isInstance());
            }
        });
    }

Take a look here:

Pau
  • 14,917
  • 14
  • 67
  • 94
  • Ok, thanks @Pau, am pretty sure that would work (have written converters before) but fairly astonished ModelMapper doesn't handle this better out-the-box. Cheers anyway. Andrew – Andrew Eells Jul 28 '16 at 12:25
  • ;) I agree. I'm not pretty sure if it is the best solution but sometimes I'm also astonished with some kind of mappings..(maybe I need to understand better the library) anyway, it is a great library. – Pau Jul 28 '16 at 14:34