Java 中继承期间通用转发的理解

Understanding of generic forwarding during inheritance in Java

我有这样的代码:

interface A<T extends A> {
    T method();
}

class AIml<T extends A> implements A<T> {
    @Override
    public T method() {
        return (T) this;
    }
}

我的问题是: 为什么不能在方法实现中写return this;

因为我在泛型擦除后不知所措,所以这段代码应该变成这样。

interface A {
    A method();
}

class AIml implements A {
    @Override
    public A method() {
        return (A)this;
    }
}

并且 class 转换变得多余。

所以是不是编译器不够聪明? 或者我错过了什么,这里会发生 ClassCastException?

您不能 return this 因为键入 AIml<T> != T。将 this 转换为 T 可能会出现意想不到的结果。

当你声明泛型类型时 <T extends A> 意味着你想要接受 一些 显式或隐式 extends/implements A 类型。不多也不少。

您可以有多种类型来满足这些要求。假设你有

class Foo implements A<Foo>{...}

甚至

class Bar implement A<Foo>{...} //<-- generic type doesn't need to be Bar,
                                //    *some* other type which extends A is OK

现在,当您将 T 声明为

class AIml<T extends A> implements A<T> {...}

您同意与之前相同的条件,因此拥有 AIml<Foo> 是合法的。问题是 FooAIml 并不真正 相关 所以你不能 return this 作为它的表示。

Or I miss something and ClassCastException can happens here?

虽然你是对的

public T method() {
    return (T) this;
}

将被删除到

public T method() {
    return (A) this;
}

它将允许您安全地使用类似

的代码
AIml<Foo> aimp = new AIml<Foo>();
A methodResult = aimp.method();

但是如果您想要将 method() 的结果保存在与 T

相同类型的引用变量中,您将得到 ClassCastException
  AIml<Foo> aimp = new AIml();
  Foo methodResult = aimp.method();
//^^^-- since method() returned AIml, not Foo