Why does javac insert Objects.requireNonNull(this) for final fields? Why does javac insert Objects.requireNonNull(this) for final fields? java java

Why does javac insert Objects.requireNonNull(this) for final fields?


Since the field is not only final, but a compile-time constant, it will not get accessed when being read, but the read gets replaced by the constant value itself, the iconst_5 instruction in your case.

But the behavior of throwing a NullPointerException when dereferencing null, which would be implied when using a getfield instruction, must be retained¹. So when you change the method to

int sumA() {  Temp t = this;  return 1 + t.field;}

Eclipse will insert an explicit null check too.

So what we see here, is javac failing to recognize that in this specific case, when the reference is this, the non-null property is guaranteed by the JVM and hence, the explicit null check is not necessary.

¹ see JLS §15.11.1. Field Access Using a Primary:

  • If the field is not static:

    • The Primary expression is evaluated. If evaluation of the Primary expression completes abruptly, the field access expression completes abruptly for the same reason.
    • If the value of the Primary is null, then a NullPointerException is thrown.
    • If the field is a non-blank final, then the result is the value of the named member field in type T found in the object referenced by the value of the Primary.