如何测试一个java类是否在运行时扩展另一个?

时间:2021-11-02 20:56:18

How to I test if a is a subclass of b?

如何测试a是否是b的子类?

Class<?> a = A.class;
Class<?> b = B.class;

3 个解决方案

#1


214  

Are you looking for:

你在找:

Super.class.isAssignableFrom(Sub.class)

#2


76  

If you want to know whether or not a Class extends another, use Class#isAssignableFrom(Class). For your example, it would be:

如果您想知道一个类是否扩展另一个类,请使用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 answer as well.

如果你想检查直接超类/子类关系,Tim也提供了答案。

#3


37  

You want to know if b is assignable from a:

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

b.isAssignableFrom(a);

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

另外,如果你想知道a是b的直接子类:

a.getSuperclass().equals(b);

#1


214  

Are you looking for:

你在找:

Super.class.isAssignableFrom(Sub.class)

#2


76  

If you want to know whether or not a Class extends another, use Class#isAssignableFrom(Class). For your example, it would be:

如果您想知道一个类是否扩展另一个类,请使用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 answer as well.

如果你想检查直接超类/子类关系,Tim也提供了答案。

#3


37  

You want to know if b is assignable from a:

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

b.isAssignableFrom(a);

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

另外,如果你想知道a是b的直接子类:

a.getSuperclass().equals(b);