Reputation: 431
Is it possible to make non-nullable type in Java? Objects of this type shouldn't can be null. How?
Upvotes: 13
Views: 16115
Reputation: 169
You can't do it in pure java, but the annotation @nonnull
will tell the compiler to test for possible paths in which the object is assigned a null value. It then throws a build error requiring you to fix the object having a null value.
Upvotes: 0
Reputation: 65811
I have recently come across the Checker Framework which has a checker for null.
@Nullable indicates a type that includes the null value. For example, the type Boolean is nullable: a variable of type Boolean always has one of the values TRUE, FALSE, or null.
@NonNull indicates a type that does not include the null value. The type boolean is non-null; a variable of type boolean always has one of the values true or false. The type @NonNull Boolean is also non-null: a variable of type @NonNull Boolean always has one of the values TRUE or FALSE — never null. Dereferencing an expression of non-null type can never cause a null pointer exception.
@PolyNull indicates qualifier polymorphism. For a description of @PolyNull, see Section 19.2.
@MonotonicNonNull indicates a reference that may be null, but if it ever becomes non-null, then it never becomes null again. This is appropriate for lazily-initialized fields, among other uses. When the variable is read, its type is treated as @Nullable, but when the variable is assigned, its type is treated as @NonNull.
I have not had time yet to try it out.
Upvotes: 7
Reputation: 234695
You can't do this in pure Java. A null
in Java is a literal value of a reference to a particular object.
Since all objects in Java are reference types, not allowing a null
does not make grammatical sense.
Upvotes: 0
Reputation: 533500
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.
Upvotes: 14
Reputation: 68935
You cannot do that. It is a language feature. At most what you can do is put null checks.
Upvotes: 0