Should javac find methods outside an anonymous class with the same name?

This question is a continuation: Why can't I call a method outside of an anonymous class with the same name

This previous question answer why , but now I want to know if javac should find run (int bar)? (See the previous question for why run (42) is executing)

If it is not, is it because of the specification? Does it produce ambiguous code? I think this is a mistake. Although the previous question explained why this code was not compiled, I believe that it should compile if javac searched above in the tree, if it could not find a match at the current level. IE If this.run () does not match, it should automatically check NotApplicable.this for the execution method.

Also note that foo (int bar) is correctly found. If you give any reason why run (int bar) should not be found, it should also explain why foo (int bar) was found.

public class NotApplicable { public NotApplicable() { new Runnable() { public void run() { // this works just fine, it automatically used NotApplicable.this when it couldn't find this.foo foo(42); // this fails to compile, javac find this.run(), and it does not match run(42); // to force javac to find run(int bar) you must use the following //NotApplicable.this.run(42); } }; } private void run(int bar) { } public void foo(int bar) { } } 
+4
source share
3 answers

This javac behavior is compliant. See §15.12 Method invocation expressions in the Java Language Specification, in particular the clause in the section “Compilation Time 1” for the meaning of invoking an unqualified method

If the Identifier appears within the scope (§6.3) of the declaration of a visible method with this name, then there must be a type declaration of the enclosing type of which this method is a member. Let T be the innermost declaration of this type. The class or interface to search is T.

In other words, an unskilled method is searched in all encompassing areas, and the innermost “type declaration” (which means either a class or an interface declaration) in which the name is located is the one that will search for the entire signature (in the “Time” section compilation 2 ").

+4
source

It sounds like a recipe for ambiguity and fragility for me - as soon as a new method is added to your base class (well, not so likely for the interface ...), the meaning of your code changes completely.

Anonymous classes are already pretty ugly, which makes this bit explicit doesn't bother me at all.

+1
source

Try

 NotApplicable.this.run(42); 

instead.

+1
source

All Articles