1

I want to avoid the human mistake in mapping objects together so I use the map-struct package. but there are situations I should manually assign fields like renaming them. like this method

@Mapper(componentModel = "spring")
public interface ItemMapper extends EntityMapper<ItemDTO, Item> {
 @Mapping(target = "itemTeplate", source = "template")
 Item toEntity(Entity entity);
}

Is there any way to generate the class field names dynamically for this usage and get an error when changing the naming and have an autocomplete class like fields? like below picture

@Mapper(componentModel = "spring")
public interface ItemMapper extends EntityMapper<ItemDTO, Item> {
 @Mapping(target = EntityFields.ITEM_TEMPLATE, source = ItemFields.TEMPLATE)
 Item toEntity(Entity entity);
}
Ali Malek
  • 578
  • 8
  • 26
  • 2
    Please [edit] the question and add the code as text, not as image. – Turing85 Dec 28 '20 at 14:18
  • Does this answer your question? [How to supply value to an annotation from a Constant java](https://stackoverflow.com/questions/2065937/how-to-supply-value-to-an-annotation-from-a-constant-java) – Progman Dec 28 '20 at 14:32
  • @Progman no I don't want for adding and removing fields from the class update two parts of the code. – Ali Malek Dec 28 '20 at 14:35

1 Answers1

1

MapStruct is an annotation processor and code generator which internals work based on the reflection. The reflection-based look-up for the fields and getters/setters is based on the String matching.

I fully understand your worries, however, consider these facts:

  • Replacing such string literal with enumeration doesn't help you much and adds only an additional layer. As long as the object field is changed, the enumeration has to be changed as well. To be the devil's advocate, I admit you might want to use it anyway in case of a lot of similar mappings - however, for that I remind you that the mappings can be inherited.
  • On compilation, MapStruct correctly throws a warning when a field is unmapped, which might happen when a new field is added. If the field is not found at all, i.e. the field is either modified or removed, the compilation fails. MapStruct follows the fail-fast principle.
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183