Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I determine if a class extends another class in Java?

Tags:

java

In Java how do I go about determining what classes a class extends?

public class A{ }  public class B extends A{ }  public class C extends A{ }  public class D{ }  public class E extends B{ }  public class doSomething{      public void myFunc(Class cls){          //need to check that cls is a class which extends A          //i.e. B, C and E but not A or D     } } 

would cls.getSuperClass() do what I need?

like image 399
Iain Sproat Avatar asked Nov 04 '10 19:11

Iain Sproat


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.

Which class is extended by all other classes?

Object class is superclass of all classes. Class Object is the root of the class hierarchy. Every class has Object as a superclass.

Can a class extend another class in Java?

The extends keyword extends a class (indicates that a class is inherited from another class). In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories: subclass (child) - the class that inherits from another class.

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.


1 Answers

The getSuperClass() approach would fail for E since its immediate superclass is not A, but B. Rather use Class#isAssignableFrom().

public void myFunc(Class cls){      //need to check that cls is a class which extends A      //i.e. B, C and E but not A or D       if (cls != A.class && A.class.isAssignableFrom(cls)) {          // ...      } } 
like image 198
BalusC Avatar answered Oct 18 '22 00:10

BalusC