jborgers / PMD-jPinpoint-rules

PMD rule set for responsible Java and Kotlin coding: performance, sustainability, multi-threading, data mixup and more.
Apache License 2.0
43 stars 10 forks source link

Fix request: False positive in AvoidObjectMapperAsField #370

Open basvz opened 1 month ago

basvz commented 1 month ago

In order to change how JacksonJsonProvider maps JSON ("application/json") content to and from Java Objects ("POJO"s). You can use a ContextResolver implementation like this

public class MapperContextResolver implements ContextResolver<ObjectMapper> {

    private final ObjectMapper mapper;

    public MapperContextResolver() {
        mapper = new ObjectMapper();
        // do any configurations to mapper
    }

    @Override
    public ObjectMapper getContext(Class<?> cls) {
        return mapper;
    }
}

JacksonJsonProvider expects a ObjectMapper so you cannot return a ObjectReader or ObjectWriter. So in this case you would want the ObjectMapper als a field, because then it can be created one time in the constructor or static block instead of in the getContext method which would break the ObjectMapperCreatedForEachMethodCall rule

jborgers commented 3 days ago

Thanks for reporting, we will look into it. Priority is still to migrate to pmd-7 fully with little false positives. When done, this issue can be picked up.