Loosening requirements for super() invocation
Brian Goetz
brian.goetz at oracle.com
Tue Nov 8 21:00:23 UTC 2022
>
> The goal is to close off all routes by which 'this' could end up being
> passed to code in any subclass.
any other class outside this compilation unit: subclass, superclass,
random class. This is sometimes called "alien" code -- code this class
does not control. (Note that inner classes in the current class are OK;
it's under this classes control.)
> Attempt #1...
>
> A 'this' escape is when, in a non-final class MyClass constructor,
> after a super() call, a reference to the 'this' instance is used,
> explicitly or implicitly, in any expression that (as far as the
> compiler can tell) might possibly:
>
> 1. Invoke a non-static method declared in any strict supertype of MyClass
>
Declared outside the compilation unit of MyClass
> 1. Otherwise access a field or invoke a non-static method declared in
> any subclass of MyClass
>
Plus:
5. Store `this` to any variable.
> Test case 2: the class below should not generate a warning. It doesn't
> because resetBoard() is private and contains no 'this' escapes.
>
> public class TicTacToe {
>
> private final char[][] board = new char[3][3];
>
> public TicTacToe() {
> this.resetBoard();
> }
>
> private void resetBoard() {
> Stream.of(this.board).forEach(row -> Arrays.fill(row, ' '));
> }
>
> // more stuff here...
> }
>
> Test case 3: FilteredSet does not generate a warning. Instead, we are
> putting the "blame" on HashSet.
>
Here's a more advanced case that would require more sophisticated data
flow analysis, but might not be so bad:
public class X {
public X() { foo(this); }
private static void foo(X x) { }
}
Here, you pass `this` to foo(), but it doesn't do anything bad with it.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20221108/f349fb1c/attachment.htm>
More information about the amber-dev
mailing list