[ACCEPTED]-How do I determine if a class extends another class in Java?-java

Accepted answer
Score: 57

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)) {
         // ...
Score: 7

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.

Score: 5

Yes, Class.getSuperclass() is exactly what you need.

Class<?> c = obj.getClass();
System.out.println(c.getSuperclass() == Some.class);


Score: 1

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