Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if one java class extends another at runtime?

People also ask

How do you check if a class extends another class in Java?

You can also use getSuperclass() method to see if your class or instance of it extends from another class, and getInterfaces() to list all the interfaces your class implements.

How will you check if a class is a child 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 two classes extend each other Java?

However, Java doesn't support multiple inheritances. This means you can't extend two or more classes in a single class. When you need to extend two or more classes in Java, you need to refactor the classes as interfaces. This is because Java allows implementing multiple interfaces on a single class.

Can you extend a class that extends another class Java?

It is not possible to extend multiple classes in Java because there is no support for multiple inheritances in Java. And therefore we cannot write multiple class names after the extended keyword. But, multiple classes can inherit from a single class as java supports hierarchical inheritance.


Are you looking for:

Super.class.isAssignableFrom(Sub.class)

If you want to know whether or not a Class extends another, use Class#isAssignableFrom(Class). For your example, it would be:

if(B.class.isAssignableFrom(A.class)) { ... }

If you're interested in whether or not an instance is of a particular type, use instanceof:

A obj = new A();
if(obj instanceof B) { ... }

Note that these will return true if the class/instance is a member of the type hierarchy and are not restrictive to direct superclass/subclass relationships. For example:

// if A.class extends B.class, and B.class extends C.class
C.class.isAssignableFrom(A.class); // evaluates to true
// ...and...
new A() instanceof C; // evaluates to true

If you want to check for direct superclass/subclass relationships, Tim has provided an answer as well.


You want to know if b is assignable from a:

b.isAssignableFrom(a);

Additionally, if you want to know that a is a direct subclass of b:

a.getSuperclass().equals(b);