在java泛型中,若需声明一个可接受所有实现特定接口(如isomething)的类的class引用,应使用通配符上界语法class extends isomething>,而非class
要理解这一设计,关键在于明确 Class
由于 A 和 B 都实现了 ISomething,它们在类型关系上满足 A <: isomething b class> 和 Class 都是 Class extends ISomething> 的子类型,可安全赋值:
interface ISomething { void doSomething(); }
class A implements ISomething {
public void doSomething() { System.out.println("A"); }
}
class B extends A {
@Override
public void doSomething() { System.out.println("B"); }
}
// ✅ 正确:声明支持所有 ISomething 实现类的 Class 引用
Class extends ISomething> clazz;
clazz = A.class; // OK: Class → Class extends ISomething>
clazz = B.class; // OK: Class → Class extends ISomething>
// clazz = String.class; // ❌ 编译错误:String 不实现 ISomething
// ⚠️ 注意:ISomething.class 也可赋值(因接口自身满足 ? extends ISomething),
// 但通常无实际构造意义,慎用于 newInstance()
clazz = ISomething.class; // 编译通过,但 clazz.asSubclass(ISomething.class) 会失败⚠️ 重要注意事项:
try {
ISomething instance = clazz.asSubclass(ISomething.class)
.getDeclaredConstructor()
.newInstance();
i
nstance.doSomething();
} catch (Exception e) {
throw new RuntimeException("Cannot instantiate " + clazz, e);
}综上,Class extends ISomething> 是表达“任意实现 ISomething 的具体类的 Class 对象”的标准、类型安全且符合 Java 泛型规范的方式。