如何在运行时测试一个 java 类是否扩展了另一个 java 类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3504870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to test if one java class extends another at runtime?
提问by Armand
How to I test if a
is a subclass of b
?
如何测试是否a
是 的子类b
?
Class<?> a = A.class;
Class<?> b = B.class;
采纳答案by meriton
Are you looking for:
您是否正在寻找:
Super.class.isAssignableFrom(Sub.class)
回答by Rob Hruska
If you want to know whether or not a Class
extends another, use Class#isAssignableFrom(Class). For your example, it would be:
如果您想知道 a 是否Class
扩展了另一个,请使用Class#isAssignableFrom(Class)。对于您的示例,它将是:
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. For example:
请注意,true
如果类/实例是类型层次结构的成员并且不受直接超类/子类关系的限制,则这些将返回。例如:
// 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 answeras well.
如果您想检查直接的超类/子类关系,Tim 也提供了答案。
回答by Tim Stone
You want to know if b
is assignable froma
:
b.isAssignableFrom(a);
Additionally, if you want to know that a
is a direct subclass of b
:
此外,如果您想知道它a
是 的直接子类b
:
a.getSuperclass().equals(b);