[英]Passing Class objects in java
I have an Interface and 2 concrete class that implement that interface, 我有一个接口和2个实现该接口的具体类,
public interface ITemplate{}
public Template implements ITemoplate {}
public Template2 implements ITemplate {}
I have a method that takes in the Class object and instantiates it. 我有一个接受Class对象并实例化它的方法。
public addTemplate(Class<ITemplate> template){
pipe.add(template.newInstance())
}
The problem is that when I call that method, it throws a compile time error: 问题是,当我调用该方法时,它会抛出编译时错误:
instance.addTemplate(Template.class)
Compile Time Error : 编译时错误:
addTemplate(java.package.ITemplate.class) cannot be applied to addTemplate(java.package.Template.class)
Am I missing something, or is there a work around for this? 我错过了什么,或者有解决方法吗?
Class<ITemplate>
will strictly accept the ITemplate.class
Class<ITemplate>
将严格接受ITemplate.class
Class<? extends ITemplate>
Class<? extends ITemplate>
will accept any of the classes implementing ITemplate.class
Class<? extends ITemplate>
将接受任何实现ITemplate.class
的类
try this method: 试试这个方法:
// works for all classes that inherit from ITemplate.
public addTemplate(Class< ? extends ITemplate> template){
pipe.add(template.newInstance())
}
instead of 代替
// only accepts ITemplate Type Class (Strict Type).
public addTemplate(Class<ITemplate> template){
pipe.add(template.newInstance())
}
Here is an explanation: when you use Class<ITemplate>
it is a strict type of class Itemplate
. 这是一个解释:当你使用Class<ITemplate>
它是一个严格类型的Itemplate
。 It will never take any other type argument other than ITemplate
, because it is resolved at compile time only. 它永远不会采用除ITemplate
之外的任何其他类型参数,因为它仅在编译时解析。 However Class <? extends ITemplate>
然而Class <? extends ITemplate>
Class <? extends ITemplate>
can accept all objects that are either ITemplate
or have ITemplate
as a superclass. Class <? extends ITemplate>
可以接受所有ITemplate
或ITemplate
作为超类的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.