以下内容会引发编译错误,因为 foo.getClass() 与 F 以某种方式扩展 Foo 的捕获组不同:
public <F extends Foo> F create (final F foo){
return foo.getClass().cast(foo);
}
以下工作正常。
return foo;
谢谢。
最佳答案
Object#getClass()
returns a Class<? extends Foo>
,不是Class<F extends Foo>
.
The actual result type is
Class<? extends |X|>
where|X|
is the erasure of the static type of the expression on which getClass is called.
删除<F extends Foo>
是上限,Foo
。因此Class#cast()
调用大致相当于
return (Foo) foo;
而不是
return (F) foo;
正如您现在可能已经发现的那样,Foo
不是F extends Foo
(声明的方法返回类型),所以编译器不会让你返回 Foo
.
关于java - 编译器提示强制转换为同一捕获组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12289573/