As noted by other answers, Intellij implemented a process to add the null checks to your code before it is compiled. There is one unofficial maven plugin (https://github.com/osundblad/intellij-annotations-instrumenter-maven-plugin) and some forks of it, but it is not longer maintained (last change was over a year ago) and I couldn't get it to work.
Thus, I recommend using another annotation instead. In my project, I switched to Lombok instead, which also has some nice additional features. To get it to work, you explicitly need to tell Lombok to throw another exception. See this working example:
Prequisites:
You need to add the lombok dependency to your maven pom.xml (find the latest version here):
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
In your root directory (inside the folder, that contains 'src') create a lombok.config with the following content:
lombok.nonNull.exceptionType=IllegalArgumentException
1. Use case
Now you can use the @NonNull
annotation for parameters and the null-checks will be generated automatically. You probably also need to add the maven-surefire-plugin to your pom.xml.
2. Use case
There is a neat possibility to let Lombok figure out itself, when the null check is necessary and when not for constructors. The following code will generate a constructor with to parameters (list1, list2). But it will only throw an IllegalArgmentException/NullPointerException, if the argument 'list1' is null
, because list2 is not annotated with @NonNull
.
import lombok.RequiredArgsConstructor;
import java.util.List;
@RequiredArgsConstructor
public class A {
@NonNull
private final List<String> list1;
private final List<String> list2;
...
}