9

Let's say I have two Class objects. Is there a way to check whether one class is a subtype of the other?

 public class Class1 { ... }

 public class Class2 extends Class1 { ... }

 public class Main {
   Class<?> clazz1 = Class1.class;
   Class<?> clazz2 = Class2.class;

   // If clazz2 is a subtype of clazz1, do something.
 }
BJ Dela Cruz
  • 5,194
  • 13
  • 51
  • 84
  • 4
    Are you looking for: http://stackoverflow.com/questions/3504870/how-to-test-if-one-java-class-extends-another-at-runtime – JRaymond Apr 27 '12 at 05:12

2 Answers2

11
if (clazz1.isAssignableFrom(clazz2)) {
    // do stuff
}

This checks if clazz1 is the same, or a superclass of clazz2.

Travis Webb
  • 14,688
  • 7
  • 55
  • 109
2

You can check like this:

if(Class1.class.isAssignableFrom(Class2.class)){

}
Nishant
  • 32,082
  • 5
  • 39
  • 53