在这段代码中,为什么类型不能声明为Class<? extends B>
?
public class Foo<B> {
public void doSomething(B argument) {
Class<? extends Object> type = argument.getClass();
}
}
最佳答案
这个问题是 Java 的语法不允许 getClass() 说它返回的类型与其定义的类相匹配,并且就编译器而言,这不是特例。所以你被迫转换结果。
在很多情况下,您希望能够指定 this
类型,例如用于链接,所以我希望他们有一天能包含这个功能。
你可以写
Class<? extends this> getClass();
或者
public this clone(); // must return a type of this class.
或者
class ByteBuffer {
this order(ByteOrder order);
}
class MappedByteBuffer extends ByteBuffer {
}
// currently this won't work as ByteBuffer defines order()
MappedByteBuffer mbb = fc.map(MapMode.READ_WRITE, 0, fc.size())
.order(ByteOrder.nativeOrder());
关于java - 在这种情况下,为什么 Class 没有一个很好的泛型类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13739800/