这是一个例子:
class test {
static interface I<A> { }
static class Y implements I<Integer> { }
public static void main(String[] args) {
// this is not allowed by the compiler:
//I<String> s = new Y() ;
// yet:
System.out.println(">" + I.class.isAssignableFrom(Y.class)) ; // true!
}
}
因此,我得出的结论是 isAssignable 的答案并不总是正确的。这是一个正确的结论吗?有没有更好的方法来在运行时检查子类型?
谢谢。 ——愿望。
最佳答案
你被类型删除绊倒了。 isAssignableFrom
方法对删除(原始)类型进行操作 I
。另一方面,编译器看到您尝试分配 I<Integer>
到I<String>
,并不允许分配。
您可以通过 getGenericInterfaces 确定实际实现的类型等等人。然后您可以检查返回的类型是否为 ParamterizedType
的实例。 ,并获取实际的类型绑定(bind)。
不过,通常情况下,这是很少有必要的。
关于java - 我可以使用 isAssignableFrom 来检查 Java 中 C1 是 C2 的子类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22881164/