Java Lombok | Null Checks for Method Arguments - @NonNull
@NonNull
If you annotate a method argument with @NonNull, a null check is generated automatically.
package com.devkuma.tutorial.lombok;
import lombok.NonNull;
public class NonNullTutorial {
public static void main(String[] args) {
method("devkuma");
method(null);
}
private static void method(@NonNull String value) {
System.out.println(value);
}
}
Execution result:
devkuma
Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.1.1/userguide/command_line_interface.html#sec:command_line_warnings
2 actionable tasks: 2 executed
Exception in thread "main" java.lang.NullPointerException: value is marked non-null but is null
at com.devkuma.tutorial.lombok.NonNullTutorial.method(NonNullTutorial.java:11)
at com.devkuma.tutorial.lombok.NonNullTutorial.main(NonNullTutorial.java:8)
Because of @NonNull, the code above is transformed as follows.
package com.devkuma.tutorial.lombok;
import lombok.NonNull;
public class NonNullTutorial {
public NonNullTutorial() {
}
public static void main(String[] args) {
method("devkuma");
method((String)null);
}
private static void method(@NonNull String value) {
if (value == null) {
throw new NullPointerException("value is marked non-null but is null");
} else {
System.out.println(value);
}
}
}
- You can see that a null check for the
valuevariable was generated automatically.