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

JavaSubclassInstanceofClass Hierarchy

Java Problem Overview


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

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

Java Solutions


Solution 1 - Java

Are you looking for:

Super.class.isAssignableFrom(Sub.class)

Solution 2 - Java

If you want to know whether or not a Class extends another, use 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:

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:

// 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.

Solution 3 - Java

You want to know if b http://download-llnw.oracle.com/javase/1.5.0/docs/api/java/lang/Class.html#isAssignableFrom%28java.lang.Class%29">is assignable from a:

b.isAssignableFrom(a);

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

a.getSuperclass().equals(b);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArmandView Question on Stackoverflow
Solution 1 - JavameritonView Answer on Stackoverflow
Solution 2 - JavaRob HruskaView Answer on Stackoverflow
Solution 3 - JavaTim StoneView Answer on Stackoverflow