[ACCEPTED]-How do I determine if a class extends another class in Java?-java
The getSuperClass()
approach would fail for E
since its 2 immediate superclass is not A
, but B
. Rather 1 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)) {
// ...
}
}
You should try to avoid type checking and 9 instead implement functions in B, C and 8 E that do what you want, have the A and 7 D versions do nothing, and then call that 6 function from within your doSomething class.
If 5 you do type checking it's not very maintainable 4 because when you add new classes you need 3 to change the conditional logic.
It's this 2 problem that classes and overriding are 1 there to prevent.
Yes, Class.getSuperclass()
is exactly what you need.
Class<?> c = obj.getClass();
System.out.println(c.getSuperclass() == Some.class);
0
If you want compile time checking, you can 3 use Generics (Java 5 and up):
public void myFunc(Class<? extends A> cls) {
}
Passing in 2 any Class not inherited from A generates 1 a compile time error.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.