[英]How to test if one java class extends another at runtime?
How to I test if a
is a subclass of b
? 如何测试
a
是否是b
的子类?
Class<?> a = A.class;
Class<?> b = B.class;
您是否在寻找:
Super.class.isAssignableFrom(Sub.class)
If you want to know whether or not a Class
extends another, use Class#isAssignableFrom(Class) . 如果您想知道某个
Class
是否扩展了另一个,请使用Class#isAssignableFrom(Class) 。 For your example, it would be: 以您的示例为例:
if(B.class.isAssignableFrom(A.class)) { ... }
If you're interested in whether or not an instance is of a particular type, use instanceof
: 如果您对实例是否为特定类型感兴趣,请使用
instanceof
:
A obj = new A();
if(obj instanceof B) { ... }
Note that these will return true
if the class/instance is a member of the type hierarchy and are not restrictive to direct superclass/subclass relationships. 请注意,如果类/实例是类型层次结构的成员,并且不限于直接超类/子类关系,则它们将返回
true
。 For example: 例如:
// if A.class extends B.class, and B.class extends C.class
C.class.isAssignableFrom(A.class); // evaluates to true
// ...and...
new A() instanceof C; // evaluates to true
If you want to check for direct superclass/subclass relationships, Tim has provided an answer as well. 如果要检查直接的超类/子类关系, Tim也提供了答案 。
You want to know if b
is assignable from a
: 您想知道
b
是否可从 a
分配 :
b.isAssignableFrom(a);
Additionally, if you want to know that a
is a direct subclass of b
: 另外,如果您想知道
a
是b
的直接子类:
a.getSuperclass().equals(b);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.