如何在运行时测试一个 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 01:22:41  来源:igfitidea点击:

How to test if one java class extends another at runtime?

javasubclassinstanceofclass-hierarchy

提问by Armand

How to I test if ais 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 Classextends 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 trueif 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 bis assignable froma:

您想知道是否b可以从a以下位置分配

b.isAssignableFrom(a);

Additionally, if you want to know that ais a direct subclass of b:

此外,如果您想知道它a是 的直接子类b

a.getSuperclass().equals(b);