【发布时间】:2008-10-31 17:15:49
【问题描述】:
这个问题是对以下问题的跟进: Why can’t I call a method outside of an anonymous class of the same name
上一个问题回答了why,但是现在我想知道javac是否应该 find 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) {
}
}
【问题讨论】:
标签: java methods javac anonymous-class