Make non-nullable type in Java

java, null, nullable

Solution

It is a reasonably common practice to use an @NotNull annotation which is supported by some IDEs and maven plugins. In Java 8 you can write

@NotNull String text;
@NotNull List<@NotNull String> strings = ...;

This is not a language feature, but if you need this, it is available.

Note: there isn't a standard @NotNull annotation :( So the tools which support this allow you to configure which one(s) you want. I use the one which comes with IntelliJ. It gives you warnings in the editor with auto-fixes and add runtime checks for `null` arguments, return values and variables.

Note: IntelliJ is able to work out if a field is not nullable by usage as well.

Problem

Is it possible to make non-nullable type in Java? Objects of this type shouldn't can be null. How?

Original source