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?
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.
Object class is superclass of all classes. Class Object is the root of the class hierarchy. Every class has Object as a superclass.
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.
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.
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)) { // ... } }
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