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.
 }
                Python issubclass() is built-in function used to check if a class is a subclass of another class or not. This function returns True if the given class is the subclass of given class else it returns False . Return Type: True if object is subclass of a class, or any element of the tuple, otherwise False.
Can an object be a subclass of another object? A. Yes—as long as single inheritance is followed.
In the absence of any other explicit superclass, every class is implicitly a subclass of Object . Classes can be derived from classes that are derived from classes that are derived from classes, and so on, and ultimately derived from the topmost class, Object .
if (clazz1.isAssignableFrom(clazz2)) {
    // do stuff
}
This checks if clazz1 is the same, or a superclass of clazz2.
You can check like this:
if(Class1.class.isAssignableFrom(Class2.class)){
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With