我希望使我的代码更具可读性,以及使用工具,如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


当前回答

如果有人只是在寻找IntelliJ类:您可以从maven存储库中使用

<dependency>
    <groupId>org.jetbrains</groupId>
    <artifactId>annotations</artifactId>
    <version>15.0</version>
</dependency> 

其他回答

在Java 8中还有另一种方法可以做到这一点。 我正在做两件事来完成我所需要的:

通过使用java.util.Optional包装可空字段,使可空字段显式地使用类型 在构造时使用java.util.Objects.requireNonNull检查所有非空字段是否为空

例子:

编辑:忽略第一个例子,我只是把这里作为评论对话的上下文。跳过这之后的推荐选项(第二个代码块)。

    import static java.util.Objects.requireNonNull;

    public class Role {

      private final UUID guid;
      private final String domain;
      private final String name;
      private final Optional<String> description;

      public Role(UUID guid, String domain, String name, Optional<String> description) {
        this.guid = requireNonNull(guid);
        this.domain = requireNonNull(domain);
        this.name = requireNonNull(name);
        this.description = requireNonNull(description);
      }
   }

所以我的问题是,我们在使用java 8时需要注释吗?

编辑:我后来发现有些人认为在参数中使用Optional是一种不好的做法,这里有一个关于赞成和反对的很好的讨论,为什么Java 8的Optional不应该在参数中使用

考虑到在参数中使用Optional不是最佳实践,我们需要2个构造函数:

public class Role {
      
      // Required fields, will not be null (unless using reflection) 
      private final UUID guid;
      private final String domain;
      private final String name;
      // Optional field, not null but can be empty
      private final Optional<String> description;

  //Non null description
  public Role(UUID guid, String domain, String name, String description) {
        this.guid = requireNonNull(guid);
        this.domain = requireNonNull(domain);
        this.name = requireNonNull(name);

        // description will never be null
        requireNonNull(description);

        // but wrapped with an Optional
        this.description = Optional.of(description);
      }

  // Null description is assigned to Optional.empty
  public Role(UUID guid, String domain, String name) {
        this.guid = requireNonNull(guid);
        this.domain = requireNonNull(domain);
        this.name = requireNonNull(name);
        this.description = Optional.empty();
      }
  //Note that this accessor is not a getter.
  //I decided not to use the "get" suffix to distinguish from "normal" getters 
  public Optional<String> description(){ return description;} 
 }

根据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背后的人之一。

不幸的是,JSR 308将不会添加比这个项目本地非空建议更多的值

Java 8将不会提供单一的默认注释或自己的Checker框架。 类似于Find-bugs或JSR 305,这个JSR由一小群主要是学术团队维护得很差。

它背后没有商业力量,因此JSR 308现在发布EDR 3 (JCP的早期草案审查),而Java 8应该在不到6个月内发布:-O 顺便说一句,类似于310。但与308不同的是,Oracle现在已经从其创始人手中接管了这一业务,以最大限度地减少它对Java平台的伤害。

每个项目、供应商和学术类,比如检查器框架和JSR 308背后的那些,都将创建自己的专有检查器注释。

让源代码在未来几年不兼容,直到找到一些流行的妥协,并可能添加到Java 9或10中,或者通过Apache Commons或谷歌Guava这样的框架;-)

由于JSR 305(其目标是标准化@NonNull和@Nullable)已经休眠了好几年,恐怕没有好的答案。我们所能做的就是找到一个务实的解决办法,我的办法是:

语法

从纯粹的风格角度来看,我想避免任何IDE,框架或任何工具包,除了Java本身。

这就排除了:

android.support.annotation edu.umd.cs.findbugs.annotations org.eclipse.jdt.annotation org.jetbrains.annotations org.checkerframework.checker.nullness.qual lombok。null

这使得我们只能使用javax.validation.constraints或javax.annotation。 前者随JEE一起提供。如果这比javax更好。注释可能最终随JSE一起出现,也可能永远不会出现,这是一个有争议的问题。 我个人更喜欢javax。注释,因为我不喜欢JEE依赖。

这就留给我们

javax.annotation

这也是最短的一个。

只有一种语法会更好:java.annotation.Nullable。随着其他课程的毕业 从javax到Java,过去的javax。注释会 向正确的方向迈出一步。

实现

我希望它们都有基本相同的琐碎实现, 但一项详细的分析表明,事实并非如此。

首先是相似之处:

@NonNull注释都有一行

public @interface NonNull {}

除了

它将其命名为@NotNull,并有一个简单的实现 javax。具有较长实现的注释 也叫@NotNull,并且有一个实现

@Nullable注释都有一行

public @interface Nullable {}

除了(再次)org.jetbrains.annotations及其琐碎的实现。

对于差异:

一个引人注目的问题是

javax.annotation javax.validation.constraints org.checkerframework.checker.nullness.qual

都有运行时注释(@Retention(runtime)),而

android.support.annotation edu.umd.cs.findbugs.annotations org.eclipse.jdt.annotation org.jetbrains.annotations

只是编译时(@Retention(CLASS))。

如本文所述,SO回答了运行时注释的影响 比人们想象的要小,但他们有好处吗 使工具能够执行运行时检查的 编译时1。

另一个重要的区别是代码中注释的使用位置。 有两种不同的方法。一些包使用JLS 9.6.4.1样式上下文。下表给出了概述:

Package FIELD METHOD PARAMETER LOCAL_VARIABLE
android.support.annotation ✔️ ✔️ ✔️
edu.umd.cs.findbugs.annotations ✔️ ✔️ ✔️ ✔️
org.jetbrains.annotation ✔️ ✔️ ✔️ ✔️
lombok ✔️ ✔️ ✔️ ✔️
javax.validation.constraints ✔️ ✔️ ✔️

org.eclipse.jdt。注释、javax。Annotation和org.checkerframework.checker. nullnness .qual使用中定义的上下文 JLS 4.11,在我看来这是正确的方法。

这就留给我们

javax.annotation org.checkerframework.checker.nullness.qual

在这一轮。

Code

为了帮助您自己进一步比较细节,我在下面列出了每个注释的代码。 为了便于比较,我删除了注释、导入和@Documented注释。 (除了Android包中的类,它们都有@Documented)。 我对行和@Target字段进行了重新排序,并规范了限定条件。

package android.support.annotation;
@Retention(CLASS)
@Target({FIELD, METHOD, PARAMETER})
public @interface NonNull {}

package edu.umd.cs.findbugs.annotations;
@Retention(CLASS)
@Target({FIELD, METHOD, PARAMETER, LOCAL_VARIABLE})
public @interface NonNull {}

package org.eclipse.jdt.annotation;
@Retention(CLASS)
@Target({ TYPE_USE })
public @interface NonNull {}

package org.jetbrains.annotations;
@Retention(CLASS)
@Target({FIELD, METHOD, PARAMETER, LOCAL_VARIABLE})
public @interface NotNull {String value() default "";}

package javax.annotation;
@TypeQualifier
@Retention(RUNTIME)
public @interface Nonnull {
    When when() default When.ALWAYS;
    static class Checker implements TypeQualifierValidator<Nonnull> {
        public When forConstantValue(Nonnull qualifierqualifierArgument,
                Object value) {
            if (value == null)
                return When.NEVER;
            return When.ALWAYS;
        }
    }
}

package org.checkerframework.checker.nullness.qual;
@Retention(RUNTIME)
@Target({TYPE_USE, TYPE_PARAMETER})
@SubtypeOf(MonotonicNonNull.class)
@ImplicitFor(
    types = {
        TypeKind.PACKAGE,
        TypeKind.INT,
        TypeKind.BOOLEAN,
        TypeKind.CHAR,
        TypeKind.DOUBLE,
        TypeKind.FLOAT,
        TypeKind.LONG,
        TypeKind.SHORT,
        TypeKind.BYTE
    },
    literals = {LiteralKind.STRING}
)
@DefaultQualifierInHierarchy
@DefaultFor({TypeUseLocation.EXCEPTION_PARAMETER})
@DefaultInUncheckedCodeFor({TypeUseLocation.PARAMETER, TypeUseLocation.LOWER_BOUND})
public @interface NonNull {}

为了完整起见,下面是@Nullable的实现:

package android.support.annotation;
@Retention(CLASS)
@Target({METHOD, PARAMETER, FIELD})
public @interface Nullable {}

package edu.umd.cs.findbugs.annotations;
@Target({FIELD, METHOD, PARAMETER, LOCAL_VARIABLE})
@Retention(CLASS)
public @interface Nullable {}

package org.eclipse.jdt.annotation;
@Retention(CLASS)
@Target({ TYPE_USE })
public @interface Nullable {}

package org.jetbrains.annotations;
@Retention(CLASS)
@Target({FIELD, METHOD, PARAMETER, LOCAL_VARIABLE})
public @interface Nullable {String value() default "";}

package javax.annotation;
@TypeQualifierNickname
@Nonnull(when = When.UNKNOWN)
@Retention(RUNTIME)
public @interface Nullable {}

package org.checkerframework.checker.nullness.qual;
@Retention(RUNTIME)
@Target({TYPE_USE, TYPE_PARAMETER})
@SubtypeOf({})
@ImplicitFor(
    literals = {LiteralKind.NULL},
    typeNames = {java.lang.Void.class}
)
@DefaultInUncheckedCodeFor({TypeUseLocation.RETURN, TypeUseLocation.UPPER_BOUND})
public @interface Nullable {}

下面两个包没有@Nullable,所以我分别列出它们;Lombok有一个非常无聊的@NonNull。 在javax.validation.constraints中@NonNull实际上是一个@NotNull 而且它的实现时间较长。

package lombok;
@Retention(CLASS)
@Target({FIELD, METHOD, PARAMETER, LOCAL_VARIABLE})
public @interface NonNull {}

package javax.validation.constraints;
@Retention(RUNTIME)
@Target({ FIELD, METHOD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Constraint(validatedBy = {})
public @interface NotNull {
    String message() default "{javax.validation.constraints.NotNull.message}";
    Class<?>[] groups() default { };
    Class<? extends Payload>[] payload() default {};
    @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
    @Retention(RUNTIME)
    @Documented
    @interface List {
        NotNull[] value();
    }
}

支持

根据我的经验,javax。注释至少被Eclipse和Checker框架开箱即用所支持。

总结

我的理想注释是java。注释语法与检查器框架实现。

如果你不打算使用检查器框架,javax。注释(JSR-305)仍然是目前最好的选择。

如果您愿意购买检查器框架,请使用 org.checkerframework.checker.nullness.qual。


来源

android.support.annotation from android-5.1.1_r1.jar edu.umd.cs.findbugs.annotations from findbugs-annotations-1.0.0.jar org.eclipse.jdt.annotation from org.eclipse.jdt.annotation_2.1.0.v20160418-1457.jar org.jetbrains.annotations from jetbrains-annotations-13.0.jar javax.annotation from gwt-dev-2.5.1-sources.jar org.checkerframework.checker.nullness.qual from checker-framework-2.1.9.zip lombok from lombok commit f6da35e4c4f3305ecd1b415e2ab1b9ef8a9120b4 javax.validation.constraints from validation-api-1.0.0.GA-sources.jar

区分静态分析和运行时分析。对内部内容使用静态分析,对代码的公共边界使用运行时分析。

对于不应该为null的东西:

Runtime check: Use "if (x == null) ..." (zero dependency) or @javax.validation.NotNull (with bean validation) or @lombok.NonNull (plain and simple) or guavas Preconditions.checkNotNull(...) Use Optional for method return types (only). Either Java8 or Guava. Static check: Use an @NonNull annotation Where it fits, use @...NonnullByDefault annotations on class or package level. Create these annotations yourself (examples are easy to find). Else, use @...CheckForNull on method returns to avoid NPEs

这应该会得到最好的结果:IDE中的警告、Findbugs和checkerframework的错误、有意义的运行时异常。

不要期望静态检查是成熟的,它们的命名不是标准化的,不同的库和ide对待它们是不同的,忽略它们。JSR305 java .annotations。*类看起来像标准的,但它们不是,它们在Java9+中会导致拆分包。

一些注释解释:

Findbugs/spotbugs/jsr305 annotations with package javax.validation.* clash with other modules in Java9+, also possibly violate Oracle license Spotbugs annotations still depends on jsr305/findbugs annotations at compiletime (at the time of writing https://github.com/spotbugs/spotbugs/issues/421) jetbrains @NotNull name conflicts with @javax.validation.NotNull. jetbrains, eclipse or checkersframework annotations for static checking have the advantage over javax.annotations that they do not clash with other modules in Java9 and higher @javax.annotations.Nullable does not mean to Findbugs/Spotbugs what you (or your IDE) think it means. Findbugs will ignore it (on members). Sad, but true (https://sourceforge.net/p/findbugs/bugs/1181) For static checking outside an IDE, 2 free tools exist: Spotbugs(formerly Findbugs) and checkersframework. The Eclipse library has @NonNullByDefault, jsr305 only has @ParametersAreNonnullByDefault. Those are mere convenience wrappers applying base annotations to everything in a package (or class), you can easily create your own. This can be used on package. This may conflict with generated code (e.g. lombok). Using lombok as an exported dependency should be avoided for libraries that you share with other people, the less transitive dependencies, the better Using Bean validation framework is powerful, but requires high overhead, so that's overkill just to avoid manual null checking. Using Optional for fields and method parameters is controversial (you can find articles about it easily) Android null annotations are part of the Android support library, they come with a whole lot of other classes, and don't play nicely with other annotations/tools

在Java9之前,这是我的建议:

// file: package-info.java
@javax.annotation.ParametersAreNonnullByDefault
package example;


// file: PublicApi
package example;

public interface PublicApi {

    Person createPerson(
        // NonNull by default due to package-info.java above
        String firstname,
        String lastname);
}

// file: PublicApiImpl
public class PublicApiImpl implements PublicApi {
    public Person createPerson(
            // In Impl, handle cases where library users still pass null
            @Nullable String firstname, // Users  might send null
            @Nullable String lastname // Users might send null
            ) {
        if (firstname == null) throw new IllagalArgumentException(...);
        if (lastname == null) throw new IllagalArgumentException(...);
        return doCreatePerson(fistname, lastname, nickname);
    }

    @NonNull // Spotbugs checks that method cannot return null
    private Person doCreatePerson(
             String firstname, // Spotbugs checks null cannot be passed, because package has ParametersAreNonnullByDefault
             String lastname,
             @Nullable String nickname // tell Spotbugs null is ok
             ) {
         return new Person(firstname, lastname, nickname);
    }

    @CheckForNull // Do not use @Nullable here, Spotbugs will ignore it, though IDEs respect it
    private Person getNickname(
         String firstname,
         String lastname) {
         return NICKNAMES.get(firstname + ':' + lastname);
    }
}

注意,当可以为空的方法参数被解引用时,没有办法让Spotbugs引发警告(在撰写本文时,Spotbugs是3.1版)。也许checkerframework可以做到。

遗憾的是,这些注释并没有区分具有任意调用点的库中的公共方法和每个调用点都可以已知的非公共方法。因此,“指示不需要null,但准备传递null”的双重含义在单个声明中是不可能实现的,因此上面的示例为接口和实现提供了不同的注释。

对于分离接口方法不实用的情况,以下方法是一种折衷方案:

        public Person createPerson(
                @NonNull String firstname,
                @NonNull String lastname
                ) {
            // even though parameters annotated as NonNull, library clients might call with null.
            if (firstname == null) throw new IllagalArgumentException(...);
            if (lastname == null) throw new IllagalArgumentException(...);
            return doCreatePerson(fistname, lastname, nickname);
        }

这有助于客户端不传递null(编写正确的代码),同时返回有用的错误。