我有一个方法将通用类接口(interface)作为参数,我想检查提供的接口(interface)是否扩展了某个基类,如果没有,我将抛出异常。是否可以做类似的事情:
public void genericMethod(Class<T> c) {
if (!(c instanceof baseClass)) {
throw new Exception("Must be instance of base class");
}
}
即使有可能,它会被视为良好做法吗?或者 Java 泛型是否应该遵循 ducktyping
的相同原则?
最佳答案
您可以使用 Class.isAssignableFrom
:
if (baseClass.isAssignableFrom(c)) {
...
}
此代码假定 baseClass
是一个类型为 Class
的变量(字段、局部变量等)。如果 baseClass
是类的名称(这将违反 Java 约定),则使用 baseClass.class
代替,如 Pshemo 在评论。
来自文档:
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.
关于java - 是否可以评估一个类接口(interface)是否扩展了某个基类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17479869/