【发布时间】:2009-07-24 10:14:47
【问题描述】:
我们有一些在 Eclipse 3.4 中编译和运行良好的单元测试,但是当我们尝试使用 javac 编译它们时,它失败了。我已经设法将代码缩减为小而独立的代码,因此它没有外部依赖项。代码本身没有多大意义,因为它完全脱离了上下文,但这没关系 - 我只需要找出 javac 不喜欢这样的原因:
public class Test {
public void test() {
matchOn(someMatcher().with(anotherMatcher()));
}
void matchOn(SubMatcher matcher) {}
SubMatcher someMatcher() {
return new SubMatcher();
}
Matcher anotherMatcher() {
return null;
}
}
interface Matcher <U, T> {}
class BaseMatcher implements Matcher {
public BaseMatcher with(Matcher<?,?> matcher) {
return this;
}
}
class SubMatcher extends BaseMatcher {
@Override
public SubMatcher with(Matcher matcher) {
return this;
}
}
我试过JDK 1.5.0_10和1.6.0_13,结果一样:
Test.java:6: matchOn(test.SubMatcher) in test.Test cannot be applied to (test.BaseMatcher)
matchOn(someMatcher().with(anotherMatcher()));
^
1 error
我认为这是完全有效的 Java。 SubMatcher.with() 方法返回比 BaseMatcher.with() 更具体的类型,但编译器似乎认为返回类型是 BaseMatcher。但是,Eclipse 编译器可能错误地允许了不应该允许的内容。
有什么想法吗?
【问题讨论】:
-
我可以在 Linux 上使用 jdk 1.6 重现此编译器错误。似乎 Java 1.5 引入的协变返回类型在此示例中无法正常工作。
标签: java compiler-construction jls