RFR: 8193904: Uninitialized final field access and qualified this

Alex Buckley alex.buckley at oracle.com
Wed Nov 2 19:46:06 UTC 2022


JLS ch.16 is specific that only `foo` and `this.foo` cause an error. See 
the definition of "access" in the opening paragraphs of the chapter.

I seem to recall some (recent?) discussion about whether other 
qualifications of foo should count as "access", but can't find it now.

Alex

On 11/2/2022 12:13 PM, Archie L. Cobbs wrote:
> 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