这段代码无法编译。我想知道我哪里出错了:
private static Importable getRightInstance(String s) throws Exception {
Class<Importable> c = Class.forName(s);
Importable i = c.newInstance();
return i;
}
Importable 是一个接口,字符串 s 是一个实现类的名称。编译器会报错:
./Importer.java:33: incompatible types
found : java.lang.Class<capture#964 of ?>
required: java.lang.Class<Importable>
Class<Importable> c = Class.forName(format(s));
感谢任何帮助!
所有的解决方案
Class<? extends Importable> c = Class.forName(s).asSubclass(Importable.class);
并且
Class<? extends Importable> c = (Class<? extends Importable>) Class.forName(s);
和
Class<?> c = Class.forName(format(s));
Importable i = (Importable)c.newInstance();
出现如下错误(我不理解):
Exception in thread "main" java.lang.IncompatibleClassChangeError: class C1
has interface Importable as super class
C1实际上正在实现Importable(因此理论上可以转换为Importable)。
IncompatibleClassChangeError
,是在forName
过程中出现的吗?或者是在newInstance
过程中出现的吗?无论如何,这完全是一个不同的问题,可能与泛型没有任何关系,你应该为此提出一个新的问题。 - polygenelubricants