我应该使用哪个@NotNull Java注释?

本文翻译自:Which @NotNull Java annotation should I use?

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. 我希望使我的代码更具可读性,并使用IDE代码检查和/或静态代码分析(FindBugs和Sonar)等工具来避免NullPointerExceptions。 Many of the tools seem incompatible with each others' @NotNull / @NonNull / @Nonnull annotation and listing all of them in my code would be terrible to read. 许多工具似乎与彼此的@NotNull / @NonNull / @Nonnull注释不兼容,并且在我的代码中列出所有这些工具都很难阅读。 Any suggestions of which one is the 'best'? 有什么建议是“最好的”吗? Here is the list of equivalent annotations I've found: 这是我发现的等效注释列表:


#1楼

参考:https://stackoom.com/question/KpBE/我应该使用哪个-NotNull-Java注释


#2楼

JSR305 and FindBugs are authored by the same person. JSR305和FindBugs由同一个人创作。 Both are poorly maintained but are as standard as it gets and are supported by all major IDEs. 两者都维护得很差,但它们是标准的,并得到所有主要IDE的支持。 The good news is that they work well as-is. 好消息是它们按原样运作良好。

Here is how to apply @Nonnull to all classes, methods and fields by default. 以下是默认情况下如何将@Nonnull应用于所有类,方法和字段。 See https://stackoverflow.com/a/13319541/14731 and https://stackoverflow.com/a/9256595/14731 请参阅https://stackoverflow.com/a/13319541/14731https://stackoverflow.com/a/9256595/14731

  1. Define @NotNullByDefault 定义@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. Add the annotation to each package: package-info.java 2.将注释添加到每个包: package-info.java

@NotNullByDefault
package com.example.foo;

UPDATE : As of December 12th, 2012 JSR 305 is listed as "Dormant". 更新 :截至2012年12月12日, JSR 305被列为“休眠”。 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. 被执行委员会评为“休眠”的JSR,或者已经达到其自然寿命终结的JSR。

It looks like JSR 308 is making it into JDK 8 and although the JSR does not define @NotNull, the accompanying Checkers Framework does. 看起来JSR 308 正在进入JDK 8,尽管JSR没有定义@NotNull,但随附的Checkers Framework确实如此。 At the time of this writing, the Maven plugin is unusable due to this bug: https://github.com/typetools/checker-framework/issues/183 在撰写本文时,由于此错误,Maven插件无法使用: https//github.com/typetools/checker-framework/issues/183


#3楼

Unfortunately, JSR 308 will not add more values than this project local Not Null suggestion here 不幸的是, JSR 308不会在这里添加比这个项目本地Not Null建议更多的值

Java 8 will not come with a single default annotation or its own Checker framework. Java 8不会带有单个默认注释或其自己的Checker框架。 Similar to Find-bugs or JSR 305 , this JSR is poorly maintained by a small bunch of mostly academic teams. 与Find-bugs或JSR 305类似,这个JSR很少由一小部分学术团队维护。

No commercial power behind it, thus JSR 308 launches EDR 3 (Early Draft Review at JCP ) NOW, while Java 8 is supposed to ship in less than 6 months:-O Similar to 310 btw. 没有任何商业力量,因此JSR 308推出了EDR 3JCP早期草案评论),而Java 8应该在不到6个月内发货:-O类似于310 btw。 but unlike 308 Oracle has taken charge of that now away from its founders to minimize harm it'll do to the Java Platform. 但与308 Oracle不同的是, 308 Oracle现在已经掌握了它的创始人,以尽量减少它对Java平台造成的伤害。

Every project, vendor and academic class like the ones behind the Checker Framework and JSR 308 will create its own proprietary checker annotation. Checker FrameworkJSR 308背后的每个项目,供应商和学术类都将创建自己的专有检查器注释。

Making source code incompatible for years to come, until a few popular compromises could be found and maybe added to Java 9 or 10 , or via frameworks like Apache Commons or Google Guava ;-) 使源代码在未来几年内不兼容,直到可以找到一些流行的妥协,并可能添加到Java 910 ,或者通过Apache CommonsGoogle Guava等框架;-)


#4楼

If you're developing for android, you're somewhat tied to Eclipse (edit: at time of writing, not anymore), which has its own annotations. 如果您正在为Android开发,那么您在某种程度上与Eclipse有关(编辑:在撰写时,不再是),它有自己的注释。 It's included in Eclipse 3.8+ (Juno), but disabled by default. 它包含在Eclipse 3.8+(Juno)中,但默认情况下禁用。

You can enable it at Preferences > Java > Compiler > Errors/Warnings > Null analysis (collapsable section at the bottom). 您可以在Preferences> Java> Compiler> Errors / Warnings> Null analysis(底部的可折叠部分)中启用它。

Check "Enable annotation-based null analysis" 选中“启用基于注释的空分析”

http://wiki.eclipse.org/JDT_Core/Null_Analysis#Usage has recommendations on settings. http://wiki.eclipse.org/JDT_Core/Null_Analysis#Usage对设置提出了建议。 However, if you have external projects in your workspace (like the facebook SDK), they may not satisfy those recommendations, and you probably don't want to fix them with each SDK update ;-) 但是,如果您的工作区中有外部项目(如facebook SDK),它们可能无法满足这些建议,您可能不希望在每次SDK更新时修复它们;-)

I use: 我用:

  1. Null pointer access: Error 空指针访问:错误
  2. Violation of null specification: Error (linked to point #1) 违反null规范:错误(链接到#1点)
  3. Potential null pointer access: Warning (otherwise facebook SDK would have warnings) 潜在的空指针访问:警告(否则facebook SDK会有警告)
  4. Conflict between null annotations and null inference: Warning (linked to point #3) 空注释与空推理之间的冲突:警告(链接到第3点)

#5楼

Another option is the annotations provided with ANTLR 4. Following Pull Request #434 , the artifact containing the @NotNull and @Nullable annotations includes an annotation processor that produces compile-time errors and/or warnings in the event one of these attributes is misused (for example, if both are applied to the same item, or if @Nullable is applied to item with a primitive type). 另一个选项是ANTLR 4提供的注释。在Pull Request#434之后 ,包含@NotNull@Nullable注释的工件包括一个注释处理器,如果其中一个属性被误用,它会产生编译时错误和/或警告(例如,如果两者都应用于同一项,或者@Nullable应用于具有基本类型的项)。 The annotation processor provides additional assurance during the software development process that the information conveyed by the application of these annotations is accurate, including in cases of method inheritance. 注释处理器在软件开发过程中提供额外的保证,即应用这些注释所传达的信息是准确的,包括在方法继承的情况下。


#6楼

If anyone is just looking for the IntelliJ classes: you can get them from the maven repository with 如果有人只是在寻找IntelliJ类:你可以从maven存储库中获取它们

<dependency>
    <groupId>org.jetbrains</groupId>
    <artifactId>annotations</artifactId>
    <version>15.0</version>
</dependency> 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值