排除 Java 泛型 class 中的参数

Excluding params in Java generic class

我有三个 classes:A、B 和 C。C extends B, B 扩展 A。 我还有通用的 class indClass2 代码如下:

indClass2.java

package myproject;

public class indClass2 <T extends A> {

    static void hello(indClass2<? super B> a){
        System.out.println("hello from super B");
    }
    static void hello(indClass2<? extends B> a){
        System.out.println("hello from extends B");
    }

}

indClass2<? super B>indClass2<? extends B> 互相排斥。

helloworld.java

package myproject;

public class helloworld {

    public static void main(String[] args) {
        indClass2<A> a = new indClass2<A>();
        indClass2<B> b = new indClass2<B>();
        indClass2<C> c = new indClass2<C>();

        indClass2.hello(a);
        indClass2.hello(b);
        indClass2.hello(c);

    }
}

我遇到了异常:

Exception in thread "main" java.lang.Error:
Unresolved compilation problem:
The method hello(indClass2<? super B>) in the type indClass2 is not applicable for the arguments (indClass2<C>)

    at myproject.helloworld.main(helloworld.java:12)

我如何在 indClass2 中为两者实现 hello()

如果你编译代码,你可以看到 erasure 正在运行 :)

error: name clash: hello(indClass2<? extends B>) and hello(indClass2<? super B>) have the same erasure
    static void hello(indClass2<? extends B> a){

indClass2<? super B> and indClass2<? extends B> are excluding each other.

看似排斥对方,但在Java世界里却不是!

这两个具有相同的擦除并且这些方法具有完全相同的签名,因此您将遇到编译错误。

name clash: hello(indClass2<? extends B>) and hello(indClass2<? super B>) 
have the same erasure

如果您这样做是为了 understand/learn 更多关于 Java 或 Type Erasure 的信息,请阅读此处的官方文档:

或在此Blog: Type Erasure

中进行深入分析