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

和自甴很熟 提交于 2020-06-08 13:13:09

问题


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.


回答1:


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.




回答2:


If you want to rule out reflection, the answer is no.

The only option you have is, installing a security manager which disallows reflection, but in which hostile environment do you expect your code to run? And even then, the user who starts the VM could add an agent, which can manipulate the bytecode.

So, as total security is concerned: no.



来源:https://stackoverflow.com/questions/62158422/in-java-is-it-possible-to-declare-a-field-that-can-never-become-null

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!