Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why @Nonnull annotation checked at runtime?

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:

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

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

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

like image 355
Dmitry Avatar asked Nov 28 '16 15:11

Dmitry


People also ask

What does @NonNull annotation do?

The @NonNull annotation is the most important among all the annotations of the null-safety feature. We can use this annotation t0 declare non-null constraint anywhere an object reference is expected: a field, a method parameter or a method's return value.

What is the use of @nullable annotation?

The @NonNull/@Nullable annotation can put in front of functions as well to indicate the return value nullability. return null; // warn: 'null' is returned by the method ... Easy, right? Keep your Billion Dollar in your pocket and enjoy using this @Nullable and @NonNull.

What is @NonNull Lombok?

The @NonNull annotation generates a null check for fields and arguments annotated with this annotation. This annotation can be used on fields, constructor arguments, and method arguments. 51. 1. import lombok.

What exception does @NotNull throw?

Hi, when using the @NotNull annotation, IntelliJ will generate bytecode to throw an IllegalArgumentException when a null is passed/returned.


1 Answers

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

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

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

like image 85
yole Avatar answered Oct 01 '22 09:10

yole