java - javac 是否应该在同名的匿名类之外查找方法?

标签 java methods javac anonymous-class

这个问题是对以下内容的跟进: Why can’t I call a method outside of an anonymous class of the same name

前一个问题回答了为什么,但现在我想知道 javac 应该 是否找到 run(int bar)? (请参阅上一个问题以了解 run(42) 失败的原因)

如果不应该,是因为规范吗?它会产生模棱两可的代码吗?我的观点是,我认为这是一个错误。虽然前面的问题解释了为什么这段代码无法编译,但我觉得如果 javac 在当前级别找不到匹配项时在树中搜索更高的位置,它应该编译。 IE。如果 this.run() 不匹配,它应该自动检查 NotApplicable.this 以查找运行方法。

另请注意,已正确找到 foo(int bar)。如果您给出不应该找到 run(int bar) 的任何理由,它还必须解释为什么找到 foo(int bar)。

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) {
    }
}

最佳答案

javac 的这种行为符合规范。参见 §15.12 Method Invocation Expressions在 Java 语言规范中,特别是“编译时步骤 1”下的段落解释了不合格方法调用的含义:

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

换句话说,未限定的方法 name 在所有封闭范围内搜索,并在其中找到名称的最内层“类型声明”(这意味着类或接口(interface)声明)是将搜索整个签名的那个(在“编译时间步骤 2”中)。

关于java - javac 是否应该在同名的匿名类之外查找方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/254260/

相关文章:

java - 在 Scene2d Actor 中绘制形状(即 Image 或 ImageTextButton)

java - 分割字符串而不丢失分割字符

java - 如何限制变量的值?

java - 如何在方法调用中传递数据并使用用户输入

java - 如何配置邮件服务器以与 JavaMail 一起使用?

java - 如何让我的程序(彩票游戏)再次检查提示?

java - 为什么 javac -proc :only option still parse java files when class files already exist?

java - 为什么 javac 1.5 与 Eclipse 编译器相比运行速度如此之慢?

javac - 为什么 Java lambda 在实例字段初始化方面与嵌套类的处理方式不同?

java - Graphics2D : Drawing black on white?