Issue
Is there any framework / compiler plugin / static analysis tool for Java that
- Enforces that all return values are non-null unless they are explicitly marked as Nullable (via annotation or another way)
- in a given list of packages
In essence that would mean enforcing the Kotlin model, where by default nothing can be null, unless it is specifically marked.
Note that a tool that just looks for @Notnull annotations and enforces only those would not be sufficient, not allowing null return values should be the default. Alternatively the tool can focus on dereferencing values that might be null and enforce that they cannot be null unless marked as such and then they may require you to do a null check.
You can obviously still bring questions that go for that kind of solution up as related questions obviously to link them together. Also happy to find out whether this has already been asked, did not find a matching existing question myself.
Solution
The Nullness Checker of the Checker Framework does this.
Regarding your first requirement, the Nullness Checker documentation says:
The most important annotations supported by the Nullness Checker are
@NonNull
and@Nullable
.@NonNull
is rarely written, because it is the default.
Regarding your second requirement, you can use the -AonlyDefs
command-line option. Its documentation says:
set the
-AonlyDefs
command-line option to a regular expression that matches class names (not file names) whose definitions should be type-checked.
It matches fully-qualified class names, so you can specify a package name.
Answered By - mernst
Answer Checked By - Robin (JavaFixing Admin)