IntelliJ IDEA complains about null check for @NotNull parameter

懵懂的女人 提交于 2019-12-01 01:34:15

问题


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

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.

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

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

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?


回答1:


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.

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.




回答2:


If the parameter for the constructor is Not Null, Then there is no point of checking for null value with and if statement.

And As we know that whatever value is held by parameter Engine is not null, this check will always be false.

So the check that is shown in your screenshot will make complete sense. If you really don't want to see the null check inspection, then disable it from the preferences section.

In short, The value you are checking is not null inside the constructor and the IDE is aware of it.



来源:https://stackoverflow.com/questions/29497755/intellij-idea-complains-about-null-check-for-notnull-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!