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

后端 未结 4 1150
长发绾君心
长发绾君心 2020-12-03 16:50

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         


        
相关标签:
4条回答
  • 2020-12-03 17:20

    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)) {
             // ...
         }
    }
    
    0 讨论(0)
  • 2020-12-03 17:30

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

    Class<?> c = obj.getClass();
    System.out.println(c.getSuperclass() == Some.class);
    
    0 讨论(0)
  • 2020-12-03 17:31

    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.

    0 讨论(0)
  • 2020-12-03 17:32

    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.

    0 讨论(0)
提交回复
热议问题