RFR: 8193904: Uninitialized final field access and qualified this

Archie L. Cobbs duke at openjdk.org
Wed Nov 2 19:13:59 UTC 2022

If a class `MyClass` has a blank final field `foo` that has not yet been assigned, the compiler prevents you from accessing it via the expressions `foo` or `this.foo`. However, it does not prevent you from accessing it via the expression `MyClass.this.foo`.

Here's a simple example:

class QualifiedThis {
    final int foo;
    QualifiedThis() {
        System.err.println(QualifiedThis.this.foo);   // should get an error here
        this.foo = 42;

This patch fixes that omission.

I couldn't find an existing method that answers the question "Is this AST tree a reference to the current instance of the class I'm now compiling?" so I wrote a new one `TreeInfo.isThisReference()`.

The question itself is a little tricky. For example, `this` alone always is, but `Foo.this` is if the class being compiled is `Foo` or any supertype of `Foo`, *except* when `Foo` is an outer class containing the class being compiled, when it instead refers to that outer instance.

On the other hand, `Foo.super` (which, unlike `Foo.this`, can only be used to invoke a method), when `Foo` is a type and not a variable, refers to the current 'this' instance when the class being compiled is `Foo` or any supertype of `Foo`, period.


Commit messages:
 - Disallow early access to final fields via qualified 'this'.

Changes: https://git.openjdk.org/jdk/pull/10956/files
 Webrev: https://webrevs.openjdk.org/?repo=jdk&pr=10956&range=00
  Issue: https://bugs.openjdk.org/browse/JDK-8193904
  Stats: 73 lines in 5 files changed: 70 ins; 0 del; 3 mod
  Patch: https://git.openjdk.org/jdk/pull/10956.diff
  Fetch: git fetch https://git.openjdk.org/jdk pull/10956/head:pull/10956

PR: https://git.openjdk.org/jdk/pull/10956

More information about the compiler-dev mailing list