【问题标题】:Weird compile-time error only when class is generic仅当类是泛型时才出现奇怪的编译时错误
【发布时间】:2020-05-22 23:56:18
【问题描述】:

以下代码编译良好:

public class Test {

    public static interface A<Y> {
        public B<Y> foo();
    }
    public static interface B<Y> extends A<Y> {
        public A<Y> bar();
    }

    private static class Impl
        implements A, B
    {
        public B foo() {
            return this;
        }
        public A bar() {
            return null;
        }
    }

}

但是当一个泛型参数被引入顶级类Test时,代码不再编译:

public class Test<X> {

    public static interface A<Y> {
        public B<Y> foo();
    }
    public static interface B<Y> extends A<Y> {
        public A<Y> bar();
    }

    private static class Impl
        implements A, B
    {
        public B foo() {
            return this;
        }
        public A bar() {
            return null;
        }
    }

}

我得到的错误是:

接口 A 不能使用不同的参数多次实现:Test.A 和 Test.A

是什么导致了这个奇怪的编译错误?有什么办法可以解决?

顺便说一下,我用的是eclipse和Java 1.8.0_144。

感谢您的帮助。

【问题讨论】:

  • 我无法重现错误,而且您的 Impl 不应该使用原始类型,您需要指定 Y,例如 implements A&lt;Integer&gt;, B&lt;Integer&gt;
  • @azro 您使用的是什么版本的 Java?你使用的是什么编译器实现?
  • Nit:接口总是静态的,不需要显式声明它们是静态的。
  • @Andy Turner 很可能是;这段代码在当前的迭代中肯定不是很漂亮,甚至不太明智,因为我已经摆弄它很长一段时间了,试图找出它为什么不能编译。
  • 它是否与javac 一起编译? Eclipse 有自己的编译器(或者至少曾经有)。

标签: java generics compiler-errors inner-classes


【解决方案1】:

正如 Andy Turner 在 cmets 中所建议的,这是一个编译器错误。使用命令行和 javac 编译时,两个版本都编译得很好。只有在 eclipse 中(使用 eclipse 编译器中的构建)才会发生错误。

出现bug的eclipse版本确实已经过时了:

版本:氧气释放 (4.7.0)

版本号:20170620-1800

该错误似乎已在更高版本的 eclipse 中得到修复。

【讨论】:

    猜你喜欢
    • 2013-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多