When using null-related annotations at global scope level, for instance using javax.annotation.ParametersAreNonnullByDefault (from
JSR-305) at package level, it means that all the parameters to all the methods included in the package will, or should, be considered
Non-null. It is equivalent to annotating every parameter in every method with non-null annotations (such as @Nonnull).
The rule raises an issue every time a parameter could be null for a method invocation, where the method is annotated as forbidding
null parameters.
@javax.annotation.ParametersAreNonnullByDefault
class A {
void foo() {
bar(getValue()); // Noncompliant - method 'bar' do not expect 'null' values as parameter
}
void bar(Object o) { // 'o' is by contract expected never to be null
// ...
}
@javax.annotation.CheckForNull
abstract Object getValue();
}
Two solutions are possible:
@javax.annotation.ParametersAreNonnullByDefault
abstract class A {
void foo() {
Object o = getValue();
if (o != null) {
bar(); // Compliant - 'o' can not be null
}
}
void bar(Object o) {
// ...
}
@javax.annotation.CheckForNull
abstract Object getValue();
}
or
@javax.annotation.ParametersAreNonnullByDefault
abstract class A {
void foo() {
bar(getValue());
}
void bar(@javax.annotation.Nullable Object o) { // annotation was missing
// ...
}
@javax.annotation.CheckForNull
abstract Object getValue();
}