2017-03-23

Java: Silence Eclipse's Null Type Safety Warnings Where It Shouldn't

So you just enabled "Null analysis" in Eclipse, and set a reasonable NonNull annotation to confom (ie. javax.validation.constraints.NotNull), also started annotating the relevant methods with it.

But.
When using the new Java 8 Streams API, Eclipse warns inside the functions you toss in, even if you've filtered out the null ones.

I'll give you an example:
// ...inside the Foo class...
public Foo(@NotNull final Bar bar) {
        this.bar = Objects.requireNonNull(bar, "Shame...");
}
// ...inside somewhere completely unrelated...
public Optional<Foo> getFoobarizedBarBaz() {
        return Optional.ofNullable(
                fooService.getBar()
                        .stream()
                                .filter(Objects::nonNull) // yeah, so no nulls, plz
                                .map(bar -> new Foo(bar /* Oh no, yellow underline*/, someLocalValue)
                                .findAny());
}

But oh, the "bar" is underlined, stating "Null type safety: The expression of type 'Bar' needs unchecked conversion to conform to '@NotNull Bar'"...

If only there were a way to resolve that...wait, there is! We can set the type of the formal parameters inside the lambda expression!
// ...inside somewhere completely unrelated...
public Optional<Foo> getFoobarizedBarBaz() {
        return Optional.ofNullable(
                fooService.getBar()
                        .stream()
                                .filter(Objects::nonNull)
                                .map((@NotNull Bar bar) -> new Foo(bar, someLocalValue)
                                .findAny());
}

Formal parameters. PARAMETERS.
@NotNull's @Target annotation includes PARAMETER.
Even it's comment states: "Formal parameter declaration".

Win.

No comments :

Post a Comment