有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java是否可以评估类接口是否扩展了某个基类?

我有一个将泛型类接口作为参数的方法,我想检查提供的接口是否扩展了某个基类,如果没有扩展,我将抛出一个异常。是否可以执行类似以下操作:

public void genericMethod(Class<T> c) {
    if (!(c instanceof baseClass)) {
        throw new Exception("Must be instance of base class");
    }
}

即使有可能,这是否被视为良好做法?或者java泛型应该遵循相同的ducktyping原则吗


共 (2) 个答案

  1. # 1 楼答案

    解决问题的核心部分;当您走上泛型的道路时,如果您有:

           public void genericMethod(Class<? extends BaseClass> c) {
              // do what you want
            }
    

    ?通配符告诉编译器只有BaseClass的子类是可接受的参数,本质上是为您执行instanceOf检查

    这几乎消除了在编译时滥用方法的可能性

    另见

  2. # 2 楼答案

    您可以使用^{}

    if (baseClass.isAssignableFrom(c)) {
      ...
    }
    

    这段代码假定baseClassClass类型的变量(字段、局部变量等)。如果baseClass是类的名称(这将违反Java约定),那么按照Pshemo在注释中的建议,使用baseClass.class

    从文件中:

    Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter.