/mapstruct-metadata-example

Example setup that uses ASM to provide MapStruct mapping info on runtime

Primary LanguageJava

MapStruct Meta Data Example

BuildTool Java-1.8 MapStruct

Example setup that provides MapStruct mapping info on runtime.

What's the target field of a mapped source field?

Why?

Because we use MapStruct for mappings between a business-model and our ui-model. When a UI client want's to get sorted data, it can specify a field from the ui-model. Our MapStructParser can get the corresponding business-model field-name and create the needed Criteria to sort it.

Example

class BusinessModel{
   String zip; 
}

class UiModel{
   String plz; 
}

public interface ModelMapping extends BridgeMapping<BusinessModel, UiModel> {
   @Mapping(source = "zip", target = "plz")
   UiModel modelToUiModel(BusinessModel model, @MappingTarget UiModel uiModel);
}

@Test
public testMappingInfo(){
   MapStructParser mappingInfo = new MapStructParser();
   mappingInfo.parseMappingInterface(ModelMapping.class);
   assertEquals("zip", mappingInfo.mapToTargetField("plz"));
}

The mappingInfo.mapToTargetField("plz") returns the mapped field of if the BusinessModel (zip).

👉 Full example: tfr.example.mapstruct.asm.MapStructParserTest

How?

The Mapping annotation from MapStruct uses RetentionPolicy.CLASS, so it's not possible to access it with reflections. This is why we use ASM (bytecode manipulation and analysis framework) to make them available at runtime.
The AnnotationParser is a general purpose annotation parser which provide a list of MethodAnnotationInfo.
The MapStructParser uses the AnnotationParser model to build a MapStructMappingInfo by collecting the Mapping-Annotations.