gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 02:18:47 27 4
gpt4 key购买 nike

这个问题是对以下内容的跟进: 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com