160

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

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

3 Answers 3

288

Are you looking for:

Super.class.isAssignableFrom(Sub.class)
0
96

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.

3
  • 2
    Actually, it B.class.isAssignableFrom(A.class), since he wants to know if A is a subclass of B.
    – meriton
    Aug 17, 2010 at 16:50
  • 1
    Ah yes, I'll change that. Usually examples are the other way around (B extending A).
    – Rob Hruska
    Aug 17, 2010 at 16:52
  • tricked ya ;-p Many thanks for the detailed answer; I'm accepting meriton's though, as it is the clearest IMO.
    – Armand
    Aug 18, 2010 at 9:12
51

You want to know if b 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);
1
  • thanks for the answer, and thanks for using a and b from the question
    – Armand
    Aug 18, 2010 at 9:13

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.