Search code examples
javanull

In Java, is it possible to declare a field that can never become null?


Let's assume we define this Book class where we ensure that isbn can never be assigned a null value:

public class Book {

  private String isbn;

  public Book(String isbn) {
    setIsbn(isbn);
  }

  public void setIsbn(String isbn) {
    if (isbn == null) {
      throw new NullPointerException();
    }

    this.isbn = isbn;
  }

  public String getIsbn() {
    return this.isbn;
  }

}

This prevents creation of a Book object where isbn is null but after a book object with a non-null isbn is created, we can modify the value via reflection and set it to null.

Is there anyway (using a trick or a Java feature) to prevent an instance of Book to ever exist in the memory where its isbn is null?

NB: this question is not about Optionals.


Solution

  • Technically references are nullable. Even though you can use final to make sure that the compiler won't let you leave a variable null, you can use reflection to remove its finality and set it to null.

    If you count out reflection, then let's say native code or Unsafe or bytecode instrumentation or so on and so on. In the end, the internal representation allows nulls, so depending on how far you'll go there'll be a way to make a variable null if you really want to, unless you specify constraints about what's allowed/possible, such as whether a SecurityManager is involved.

    If you're asking the question because you're afraid that your variable isn't safe enough from NullPointerExceptions, then using final, Objects.requireNonNull() and good design is enough.