我希望使我的代码更具可读性,以及使用工具,如IDE代码检查和/或静态代码分析(FindBugs和Sonar),以避免nullpointerexception。许多工具似乎与彼此的@NotNull/@NonNull/ @NonNull注释不兼容,在我的代码中列出所有这些工具会让人难以阅读。有没有什么建议,哪一个是“最好的”?下面是我找到的等价注释列表:

javax.validation.constraints.NotNull Created for runtime validation, not static analysis. documentation edu.umd.cs.findbugs.annotations.NonNull Used by FindBugs (dead project) and its successor SpotBugs static analysis and therefore Sonar (now Sonarqube) FindBugs documentation, SpotBugs documentation javax.annotation.Nonnull This might work with FindBugs too, but JSR-305 is inactive. (See also: What is the status of JSR 305?) source org.jetbrains.annotations.NotNull Used by IntelliJ IDEA IDE for static analysis. documentation lombok.NonNull Used to control code generation in Project Lombok. Placeholder annotation since there is no standard. source, documentation androidx.annotation.NonNull Marker annotation available in Android, provided by annotation package documentation org.eclipse.jdt.annotation.NonNull Used by Eclipse for static code analysis documentation


当前回答

如果你正在使用Spring框架构建应用程序,我建议使用来自bean Validation的javax.validation.constraints.NotNull,它被打包在以下依赖项中:

    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.1.0.Final</version>
    </dependency>

这种注释的主要优点是Spring同时支持用javax.validation.constraints.NotNull注释的方法参数和类字段。要启用支持,您需要做的是:

supply the api jar for beans validation and jar with implementation of validator of jsr-303/jsr-349 annotations (which comes with Hibernate Validator 5.x dependency): <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.4.1.Final</version> </dependency> provide MethodValidationPostProcessor to spring's context @Configuration @ValidationConfig public class ValidationConfig implements MyService { @Bean public MethodValidationPostProcessor providePostProcessor() { return new MethodValidationPostProcessor() } } finally you annotate your classes with Spring's org.springframework.validation.annotation.Validated and validation will be automatically handled by Spring.

例子:

@Service
@Validated
public class MyServiceImpl implements MyService {

  @Override
  public Something doSomething(@NotNull String myParameter) {
        // No need to do something like assert myParameter != null  
  }
}

当您尝试调用方法doSomething并传递null作为参数值时,spring(通过HibernateValidator)将抛出ConstraintViolationException。这里不需要手工工作。

您还可以验证返回值。

javax.validation.constraints.NotNull对Beans验证框架的另一个重要好处是,目前它仍在开发中,新特性计划在新版本2.0中实现。

@Nullable呢?在Beans Validation 1.1中没有类似的东西。好吧,我可以争辩说,如果你决定使用@ nonull,而不是任何没有用@NonNull注释的东西都是有效的“nullable”,所以@Nullable注释是无用的。

其他回答

根据Java 7的特性列表,JSR-308类型注释被推迟到Java 8。甚至没有提到JSR-305注释。

在最新的JSR-308草案的附录中有一些关于JSR-305状态的信息。这包括观察到JSR-305注释似乎被抛弃了。JSR-305页面还将其显示为“inactive”。

同时,实用的答案是使用最广泛使用的工具所支持的注释类型……如果情况发生变化,也要做好改变的准备。


事实上,JSR-308没有定义任何注释类型/类,而且看起来他们认为这超出了范围。(考虑到JSR-305的存在,他们是正确的)。

然而,如果JSR-308真的想要加入Java 8,那么如果人们对JSR-305重新产生兴趣,我也不会感到惊讶。AFAIK, JSR-305团队还没有正式放弃他们的工作。他们已经沉默了2年多了。

有趣的是,Bill Pugh (JSR-305的技术主管)是FindBugs背后的人之一。

JSR305和FindBugs是由同一个人编写的。两者的维护都很差,但都是标准的,并且得到所有主要ide的支持。好消息是,他们工作得很好。

下面是如何在默认情况下将@Nonnull应用到所有类、方法和字段。 参见https://stackoverflow.com/a/13319541/14731和https://stackoverflow.com/a/9256595/14731

定义@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: <ul>
     * <li>An explicit nullness annotation <li>The method overrides a method in a superclass (in which
     * case the annotation of the corresponding parameter in the superclass applies) <li> there is a
     * default parameter annotation applied to a more tightly nested element. </ul>
     * <p/>
     * @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. 将注释添加到每个包:package-info.java

@NotNullByDefault
package com.example.foo;

更新:截至2012年12月12日,JSR 305被列为“休眠”。根据文档:

被执行委员会投票为“休眠”的JSR,或者已经达到自然生命周期的JSR。

看起来JSR 308正在加入JDK 8,尽管JSR没有定义@NotNull,但是附带的Checkers框架定义了。在撰写本文时,由于这个错误,Maven插件无法使用:https://github.com/typetools/checker-framework/issues/183

如果你在做一个大项目,你最好创建自己的@Nullable和/或@NotNull注解。

例如:

@java.lang.annotation.Documented
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.CLASS)
@java.lang.annotation.Target({java.lang.annotation.ElementType.FIELD,
                              java.lang.annotation.ElementType.METHOD,    
                              java.lang.annotation.ElementType.PARAMETER,
                              java.lang.annotation.ElementType.LOCAL_VARIABLE})
public @interface Nullable 
{
}

如果您使用了正确的保留策略,那么注释在运行时将不可用。从这个角度来看,它只是一种内在的东西。

尽管这不是一门严格的科学,但我认为使用内部类是最有意义的。

这是一个内在的东西。(没有功能或技术影响) 有很多很多的用法。 像IntelliJ这样的IDE支持自定义的@Nullable/@NotNull注释。 大多数框架也喜欢使用自己的内部版本。

其他问题(见评论):

如何在IntelliJ中配置这个?

点击IntelliJ状态栏右下角的“警官”。在弹出窗口中单击“配置巡检”。下一个……

我非常喜欢检查器框架,它是类型注释(JSR-308)的实现,用于实现像null检查器这样的缺陷检查器。我并没有尝试其他任何方法进行比较,但我对这个实现感到满意。

我没有加入提供该软件的组织,但我是它的粉丝。

我喜欢这个系统的四个方面:

It has a defect checkers for nullness (@Nullable), but also has ones for immutability and interning (and others). I use the first one (nullness) and I'm trying to get into using the second one (immutability/IGJ). I'm trying out the third one, but I'm not certain about using it long term yet. I'm not convinced of the general usefulness of the other checkers yet, but its nice to know that the framework itself is a system for implementing a variety of additional annotations and checkers. The default setting for nullness checking works well: Non-null except locals (NNEL). Basically this means that by default the checker treats everyhing (instance variables, method parameters, generic types, etc) except local variables as if they have a @NonNull type by default. Per the documentation: The NNEL default leads to the smallest number of explicit annotations in your code. You can set a different default for a class or for a method if NNEL doesn't work for you. This framework allows you to use with without creating a dependency on the framework by enclosing your annotations in a comment: e.g. /*@Nullable*/. This is nice because you can annotate and check a library or shared code, but still be able to use that library/shared coded in another project that doesn't use the framework. This is a nice feature. I've grown accustom to using it, even though I tend to enable the Checker Framework on all my projects now. The framework has a way to annotate APIs you use that aren't already annotated for nullness by using stub files.

只是指出Java验证API (javax.validation.constraints.*)没有提供@Nullable注释,这在静态分析上下文中非常有价值。这对于运行时bean验证是有意义的,因为这是Java中任何非基本字段的默认值(即没有需要验证/强制的内容)。为达到上述目的,应权衡备选方案。