java 为什么在运行时检查@Nonnull 注释?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40847472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 05:30:42  来源:igfitidea点击:

Why @Nonnull annotation checked at runtime?

javaintellij-ideanon-nullable

提问by Dmitry

I have a function with following signature

我有一个带有以下签名的函数

public static String myFunction(@Nonnull String param)

When I call it with param as null, I get the following exception:

当我使用 param 为 null 调用它时,出现以下异常:

Caused by: java.lang.IllegalArgumentException: Argument for @Nonnull parameter 'param' of com/MyClass.myFunction must not be null
    at com.MyClass.$$$reportNull$$##代码##(MyClass.java) 

javax.annotation.Nonnull supposed not to be checked at runtime.

javax.annotation.Nonnull 不应该在运行时检查。

Who actually throws the exception and why?

谁实际上抛出了异常,为什么?

P.S. I run Tomcat server in debug mode from IntelliJ IDEA 2016.3 with Oracle JDK 1.8.0_102

PS我使用Oracle JDK 1.8.0_102从IntelliJ IDEA 2016.3以调试模式运行Tomcat服务器

回答by yole

When you compile your project in IntelliJ IDEA, it instruments the bytecode of compiled classes to add runtime checks for various flavors of @Nonnullannotations. This behavior is controlled by the option:

当您在 IntelliJ IDEA 中编译您的项目时,它会检测已编译类的字节码,以便为各种@Nonnull注释添加运行时检查。此行为由选项控制:

Settings | Build, Execution, Deployment | Compiler | [x] Add runtime assertions for not-null-annotated methods and parameters.

设置 | 构建、执行、部署 | 编译器 | [x] 为非空注释的方法和参数添加运行时断言。

Screenshot of "Add runtime assertions for notnull-annotated methods and parameters.

“为非空注释的方法和参数添加运行时断言的屏幕截图。