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
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)) {
// ...
}
}
Yes, Class.getSuperclass()
is exactly what you need.
Class<?> c = obj.getClass();
System.out.println(c.getSuperclass() == Some.class);
You should try to avoid type checking and instead implement functions in B, C and E that do what you want, have the A and D versions do nothing, and then call that function from within your doSomething class.
If you do type checking it's not very maintainable because when you add new classes you need to change the conditional logic.
It's this problem that classes and overriding are there to prevent.
If you want compile time checking, you can use Generics (Java 5 and up):
public void myFunc(Class<? extends A> cls) {
}
Passing in any Class not inherited from A generates a compile time error.