10

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. } 
1

2 Answers 2

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

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

Sign up to request clarification or add additional context in comments.

Comments

2

You can check like this:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.