Set findbugs NotNull as default for all classes under a package

人盡茶涼 提交于 2019-11-29 06:39:26

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.

You can do this to parameters, fileds and method return value simultaneously by putting these lines in your package-info.java:

@DefaultAnnotation(NonNull.class)
package com.my.package;

When findbugs runs on the code in that package, all methods and fields are assumed to be non-null unless you annotate them with @CheckForNull.

I also do not know of a way to make this apply to sub-packages. I do this for each package.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!