我最近被以下 Java 代码惊呆了:
interface Common {}
interface A extends Common {}
static class B implements Common {}
static class Impl {
private A a;
public <T extends A> T translate() {
return (T) a;
}
}
static class Usage {
public void use() {
Impl impl = new Impl();
B b = impl.translate(); // Why does this compile?
}
}
Run Code Online (Sandbox Code Playgroud)
我本来期望的是在类型约束Impl.translate
不会允许将结果存储在类型B
由编译器所接受,考虑到B
不延长A
。代码UncheckedCastException
在运行时抛出一个,而不是编译器错误。
这仅在方法返回类型时发生T
;如果它是方法参数:
public <T extends A> …
Run Code Online (Sandbox Code Playgroud)