Instance qualifier for static access warning and anonymous classes

Brian Goetz brian.goetz at oracle.com
Tue May 10 16:54:48 UTC 2022


In various "new" situations, we've taken the choice to close this route 
down, such as with static methods in interfaces.  Arguably, had we 
realized it, we might have done something similar with static members in 
anonymous classes (which were also new at the time), but we 
unfortunately missed this case.

I suspect that the number of cases where people actually rely on this 
feature (access a static member of an anonymous class through an 
instance) is still pretty small, so we could still consider closing it 
down after-the-fact.  May or may not be worth the fuss, as there will 
surely be some fuss.

On 4/29/2022 11:25 AM, Maurizio Cimadamore wrote:
> 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