Skip to content

Condition: Add @MappingTargetValue as parameter #4001

@newhinton

Description

@newhinton

Use case

I am currently mapping two objects where the mapping happens conditionally, based on both the source value AND the target value.

I have looked into the documentation, and the only way i found is to do something like this:

// A:
@Condition
default <T> boolean shouldMap(MatchingAttribute<T> value, @TargetPropertyName String propertyName, @MappingTarget MyClass target) {
        
        try {
            var field = target.getClass().getDeclaredField(propertyName);
            field.setAccessible(true);
            var getTargetValueByReflection = field.get(target);
            return value.subvalue == getTargetValueByReflection;

        } catch (NoSuchFieldException | IllegalAccessException e) {
            // I am aware that i can let the exceptions bubble up
            throw new RuntimeException(e);
        }
}

This works, but it is very clunky. It also requires me to use reflections that might fail with an exception.
What i'd like to use is an annotation that directly gets me the value:

// B:
@Condition
default <T> boolean shouldMap(MatchingAttribute<T> value, @MappingTargetValue T target) {
        return value.subvalue == target;
}

This is a lot less complicated to maintain.

Regardless of whether or not you accept this FR, mapstruct has already been a huge improvement to what i am doing. Thank you so much!

Generated Code

Code For A:

// A:
if ( shouldMap( entity.getAttribute(), "attribute", target ) ) {
    target.setAttribute( modify( entity.getAttribute() ) );
 }

Code For B:

// B:
if ( shouldMap( entity.getAttribute(), target.getAttribute() ) ) {
    target.setAttribute( modify( entity.getAttribute() ) );
}

Possible workarounds

See above code example using reflections

MapStruct Version

1.6.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions