Checking if a class object is a subtype of another class object in Java?

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

 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.
 }
+5
source share
2 answers
if (clazz1.isAssignableFrom(clazz2)) {
    // do stuff
}

This checks if the clazz1superclass matches either clazz2.

+8
source

You can check the following:

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

}
+1
source

All Articles