如何确定一个类是否扩展了 Java 中的另一个类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4100281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:37:33  来源:igfitidea点击:

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

java

提问by Iain Sproat

In Java how do I go about determining what classes a class extends?

在 Java 中,我如何确定一个类扩展了哪些类?

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?

cls.getSuperClass()做我需要的吗?

采纳答案by BalusC

The getSuperClass()approach would fail for Esince its immediate superclass is not A, but B. Rather use Class#isAssignableFrom().

这种getSuperClass()方法会失败,E因为它的直接超类不是A, but B。而是使用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)) {
         // ...
     }
}

回答by uckelman

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

是的,Class.getSuperclass()正是您所需要的。

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

回答by Martin Broadhurst

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.

你应该尽量避免类型检查,而是在 B、C 和 E 中实现你想要的函数,让 A 和 D 版本什么都不做,然后从你的 doSomething 类中调用该函数。

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.

正是类和覆盖要防止的这个问题。

回答by Durandal

If you want compile time checking, you can use Generics (Java 5 and up):

如果您想要编译时检查,您可以使用泛型(Java 5 及更高版本):

public void myFunc(Class<? extends A> cls) {
}

Passing in any Class not inherited from A generates a compile time error.

传入任何不是从 A 继承的类都会产生编译时错误。