类< T>和静态方法Class.forName()让我疯狂 [英] Class<T> and static method Class.forName() drive me crazy

查看:251
本文介绍了类< T>和静态方法Class.forName()让我疯狂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码不能编译。

private static Importable getRightInstance(String s) throws Exception {
 Class<Importable> c = Class.forName(s);
 Importable i = c.newInstance();
 return i;
}

其中Importable是一个接口,字符串s是实现类的名称。
编译器说:

where Importable is an interface and the string s is the name of an implementing class. The compiler says:

./Importer.java:33: incompatible types
found   : java.lang.Class<capture#964 of ?>
required: java.lang.Class<Importable>
  Class<Importable> c = Class.forName(format(s));

感谢您的帮助!

全部解决方案

All the solutions

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();

给出这个错误(我不明白):

give this error (that i don't understand):

Exception in thread "main" java.lang.IncompatibleClassChangeError: class C1 
has interface Importable as super class

其中C1实际上实现了Importable(因此它理论上可转换为Importable)。

where C1 is actually implementing Importable (so it is theoretically castable to Importable).

推荐答案

使用运行时转换:

Use a runtime conversion:

Class <? extends Importable>  c
    = Class.forName (s).asSubclass (Importable.class);

如果 s 指定一个不实现接口的类。

This will bark with an exception at runtime if s specifies a class that doesn't implement the interface.

这篇关于类&LT; T&GT;和静态方法Class.forName()让我疯狂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆