Which @NotNull Java annotation should I use?

前端 未结 22 3243
梦如初夏
梦如初夏 2020-11-22 02:44

I\'m looking to make my code more readable as well as use tooling like IDE code inspection and/or static code analysis (FindBugs and Sonar) to avoid NullPointerExceptions.

22条回答
  •  深忆病人
    2020-11-22 03:27

    JSR305 and FindBugs are authored by the same person. Both are poorly maintained but are as standard as it gets and are supported by all major IDEs. The good news is that they work well as-is.

    Here is how to apply @Nonnull to all classes, methods and fields by default. See https://stackoverflow.com/a/13319541/14731 and https://stackoverflow.com/a/9256595/14731

    1. Define @NotNullByDefault
    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;
    
    
        /**
         * This annotation can be applied to a package, class or method to indicate that the class fields,
         * method return types and parameters in that element are not null by default unless there is: 
      *
    • An explicit nullness annotation
    • The method overrides a method in a superclass (in which * case the annotation of the corresponding parameter in the superclass applies)
    • there is a * default parameter annotation applied to a more tightly nested element.
    *

    * @see https://stackoverflow.com/a/9256595/14731 */ @Documented @Nonnull @TypeQualifierDefault( { ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.METHOD, ElementType.PACKAGE, ElementType.PARAMETER, ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) public @interface NotNullByDefault { }

    2. Add the annotation to each package: package-info.java

    @NotNullByDefault
    package com.example.foo;
    

    UPDATE: As of December 12th, 2012 JSR 305 is listed as "Dormant". According to the documentation:

    A JSR that was voted as "dormant" by the Executive Committee, or one that has reached the end of its natural lifespan.

    It looks like JSR 308 is making it into JDK 8 and although the JSR does not define @NotNull, the accompanying Checkers Framework does. At the time of this writing, the Maven plugin is unusable due to this bug: https://github.com/typetools/checker-framework/issues/183

提交回复
热议问题