Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.
 }
like image 294
BJ Dela Cruz Avatar asked Apr 27 '12 05:04

BJ Dela Cruz


People also ask

How do you check if a class is subclass of another class?

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 sub class of another object?

Can an object be a subclass of another object? A. Yes—as long as single inheritance is followed.

Is every class in Java a subtype of object?

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 .


2 Answers

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

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

like image 131
Travis Webb Avatar answered Oct 03 '22 02:10

Travis Webb


You can check like this:

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

}
like image 28
Nishant Avatar answered Oct 03 '22 03:10

Nishant