Jia Zhou
Jia Zhou

Reputation: 1

mapstruct null check causes spotbug error

We have a mapstruct mapper defined for a source and a target that also use lombok.

@Value
class Source {
  @NonNull List<ElementSource> elements;
}

@Value
class Target {
  @NonNull List<ElementTarget> elements;
}

@Mapper
public interface Mapper {
  Target mapToTarget(Source source);
}

mapstruct generated mapper implementation looks like below code.

        List<ElementTarget> elements = null;

        List<Element> list = source.getColumns();
        if ( list != null ) {
            elements = new ArrayList<ElementTarget>( list );
        }
        
        Target target = new Target( elements );

        return target;

Now this piece of mapper code raises spotbug error with type NP_NULL_PARAM_DEREF: Method call passes null for non-null parameter. Because it detects elements can be null when the code creates Target object.

Now what is the best option to handle this.

  1. Suppress spotbug to ignore this error type for mapstruct generated mapper classes. But the mapper class still has a code smell here.
  2. Define a customzed mapper method for elements itself and throw exception if source object return null list.
  3. if there is a way to configure mapstruct to not generate null check for elements at all.
  4. if there is a way to configure mapstruct to throw exception when null check of elements return true.

For option 3 & 4, I can't find an answer whether mapstruct support it or not.

Upvotes: 0

Views: 1097

Answers (1)

Filip
Filip

Reputation: 21393

The ideal solution would be option 3. This is currently not supported by MapStruct. However, it is a requested feature in mapstruct/mapstruct#1243. I would suggest voting for it if you are interested in it.

Option 4 would also be a new feature, that I am not sure how much it belongs in MapStruct, but you can try raising it as a feature request to get the feedback from the community.

Upvotes: 0

Related Questions