Instance qualifier for static access warning and anonymous classes

Maurizio Cimadamore maurizio.cimadamore at oracle.com
Fri Apr 29 15:25:19 UTC 2022


Well spotted - this seems like a dark corner.

IMHO there are two possible interpretation, which depend on where we 
want to go with the warning:

1. static methods accessed through instance qualifiers are Bad, and we 
should try to wean developer off them over time (and align this with 
interface static methods). In this case the warning should stay (but of 
course the message needs to be fixed :-) ).
2. static methods accessed through instance qualifiers are a wart, but 
something we should be prepared to live with forever - best thing we can 
do in this space is to issue some "style" warnings, but nothing more 
will ever happen. In this case, for this example we should turn off the 
warning altogether.

Maurizio

On 29/04/2022 15:54, Tagir Valeev wrote:
> Hello!
>
> Consider the following code:
>
> public class Demo {
>      public static void main(String[] args) {
>          var obj = new Object() {
>              static void foo() {
>                  System.out.println("Static method of anonymous class");
>              }
>          };
>          obj.foo(); // Cannot replace instance qualifier with class reference
>      }
> }
>
> With -Xlint:static, javac reports the following warning:
>
> Demo.java:8: warning: [static] static method should be qualified by
> type name, <anonymous Demo$1>, instead of by an expression
>          obj.foo(); // Cannot replace instance qualifier with class reference
>             ^
> 1 warning
>
> It's questionable whether this warning should be reported at all, as
> it's impossible to call the static method of anonymous class with
> class name qualifier. But in any case, suggesting to use `<anonymous
> Demo$1>` as a qualifier is invalid.
>
> With best regards,
> Tagir Valeev.


More information about the compiler-dev mailing list