[英]How to parameterize generic Class before instantiation?
I am loading the db-driver based on command line parameters like this: 我正在基于这样的命令行参数加载数据库驱动程序:
Class driverClass = null;
try {
driverClass = Class.forName(dbDriver);
catch(ClassNotFoundException e) {
// Print error message here
}
Later I call driverClass.newInstance()
. 后来我调用
driverClass.newInstance()
。
How can I avoid the message 我如何避免该消息
Class is a raw type.
类是原始类型。 References to generic type
Class<T>
should be parameterized泛型类型
Class<T>
引用应参数化
If I try Class<Driver>
the Class.forName part complains about a type mismatch: 如果我尝试
Class<Driver>
则Class.forName部分会抱怨类型不匹配:
Type mismatch: cannot convert from
Class<capture#1-of ?>
toClass<Driver>
类型不匹配:无法从
Class<capture#1-of ?>
为Class<Driver>
This is weird, how can I parameterize the Class in the first line correctly? 这很奇怪,如何在第一行中正确地设置Class参数?
If you do now know the exact class name, you can specify ?
如果现在知道确切的类名称,则可以指定
?
as a type meaning any class that extends Object
: 作为一种类型,表示扩展
Object
任何类:
Class<?> driverClass = Class.forName(dbDriver);
If I try Class the Class.forName part complains about a type mismatch
如果我尝试使用Class,则Class.forName部分会抱怨类型不匹配
Well if you know the class name at compile time, why initialise the class using forName
, just do this: 好吧,如果您在编译时知道类名,为什么要使用
forName
初始化类,只需执行以下操作:
Class<Driver> driverClass = Driver.class;
If you don't know the class name at compile time, you can simply put a ?
如果您在编译时不知道类名,则可以简单地输入
?
as the type parameter: 作为类型参数:
Class<?> driverClass = null;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.