IntelliJ IDEA 抱怨 @NotNull 参数的空检查 [英] IntelliJ IDEA complains about null check for @NotNull parameter

查看:218
本文介绍了IntelliJ IDEA 抱怨 @NotNull 参数的空检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的项目中使用 Jetbrains @Nullable/@NotNull Annotations.

I want to use Jetbrains @Nullable/@NotNull Annotations in my project.

我有一个带有 @NotNull 字段的类.构造函数自然不接受 null 而是抛出异常.当然这个构造函数的参数也是用@NotNull注解的.

I have a class with a @NotNull field. The constructor naturally does not accept null but throws an exception instead. Of course the parameter of this constructor is also be annotated with @NotNull.

为什么 IntelliJ IDEA 会抱怨空检查?文档指出:

Why does IntelliJ IDEA complain about the null-check? The documentation states:

使用 NotNull 注释的元素声明空值被禁止返回(对于方法)、传递给(参数)和保持(局部变量和字段).

An element annotated with NotNull claims null value is forbidden to return (for methods), pass to (parameters) and hold (local variables and fields).

但我仍然需要在运行时检查空值,以防构建系统不理解 Annotation 并接受像 new Car(null) 这样的语句.我错了吗?

But I still have to check for null-values at runtime in case the build system does not understand the Annotation and accepts a statement like new Car(null). Am I wrong?

推荐答案

如果您使用 JetBrains @NotNull 注释,运行时断言将添加到您编译的字节码中,以保证不会在那里传递 null.那么在源代码中编写相同的检查就真的没有意义了.这种方法对我们非常有效.

If you use JetBrains @NotNull annotation, runtime assertions will be added to your compiled bytecode that'll guarantee that null is not passed there. Then it really makes no sense to write the same checks in the source code. This approach works quite well for us.

如果您使用其他注释或只是不想检测字节码,您可以通过在其上按 Alt+Enter、编辑检查设置"并选中忽略断言语句"来禁用此特定警告.IDE 会将此类条件语句视为断言.

If you use other annotations or just don't want to instrument the bytecode, you can disable this particular warning by pressing Alt+Enter on it, "Edit inspection settings" and checking "Ignore assert statements". Such conditional statements are treated as assertions by the IDE.

这篇关于IntelliJ IDEA 抱怨 @NotNull 参数的空检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆