Package org.mapstruct

Annotation Type SubclassMapping


  • @Repeatable(SubclassMappings.class)
    @Retention(CLASS)
    @Target({METHOD,ANNOTATION_TYPE})
    @Experimental
    public @interface SubclassMapping
    Configures the mapping to handle hierarchy of the source type.

    The subclass to be mapped is to be specified via source(). The subclass to map to is to be specified via target().

    This annotation can be combined with @Mapping annotations.

    
     @Mapper
     public interface MyMapper {
        @SubclassMapping (target = TargetSubclass.class, source = SourceSubclass.class)
        TargetParent mapParent(SourceParent parent);
    
        TargetSubclass mapSubclass(SourceSubclass subInstant);
     }
     
    Below follow examples of the implementation for the mapParent method. Example 1: For parents that cannot be created. (e.g. abstract classes or interfaces)
    
     // generates
     @Override
     public TargetParent mapParent(SourceParent parent) {
         if (parent instanceof SourceSubclass) {
             return mapSubclass( (SourceSubclass) parent );
         }
         else {
             throw new IllegalArgumentException("Not all subclasses are supported for this mapping. Missing for "
                        + parent.getClass());
         }
     }
     
    Example 2: For parents that can be created. (e.g. normal classes or interfaces with @Mappper( uses = ObjectFactory.class ) )
    
     // generates
     @Override
     public TargetParent mapParent(SourceParent parent) {
         TargetParent targetParent1;
         if (parent instanceof SourceSubclass) {
             targetParent1 = mapSubclass( (SourceSubclass) parent );
         }
         else {
             targetParent1 = new TargetParent();
             // ...
         }
     }
     
    Since:
    1.5
    Author:
    Ben Zegveld
    • Required Element Summary

      Required Elements 
      Modifier and Type Required Element Description
      Class<?> source  
      Class<?> target  
    • Element Detail

      • source

        Class<?> source
        Returns:
        the source subclass to check for before using the default mapping as fallback.
      • target

        Class<?> target
        Returns:
        the target subclass to map the source to.