You can do this for individual packages, but I haven't found a way to have it propagate to subpackages. For method parameters use the built-in package annotation @ParametersAreNonnullByDefault
. Apply the annotation to the package in its package-info.java
file inside the package's directory.
Note that I'm using the javax.annotation
annotations from JSR-305 which FindBugs honors.
com/example/foo/package-info.java
/**
* Package that doesn't allow null values as method parameters.
*/
@ParametersAreNonnullByDefault
package com.example.foo;
import javax.annotation.ParametersAreNonnullByDefault;
For fields and method return values you'll need to create your own annotations. I did this by copying the source for ParametersAreNonnullByDefault
and changing the ElementType
enum.
com/example/util/FieldsAreNonnullByDefault.java
package com.example.util;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.annotation.Nonnull;
import javax.annotation.meta.TypeQualifierDefault;
/**
* Applies the {@link Nonnull} annotation to every class field unless overridden.
*/
@Documented
@Nonnull
@TypeQualifierDefault(ElementType.FIELD) // <-- use METHOD for return values
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldsAreNonnullByDefault
{
// nothing to add
}
I began rewriting a fairly complex system from scratch a couple months ago, and every package has these three annotations applied (fields, parameters, and return values). One benefit that's come out of the incentive to avoid null
values is using the Null Object pattern where appropriate. That combined with favoring final fields as much as possible and small classes that do one thing only has really kept the code clean.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…