Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在java中传递类对象_Java_Class - Fatal编程技术网

在java中传递类对象

在java中传递类对象,java,class,Java,Class,我有一个接口和两个实现该接口的具体类 public interface ITemplate{} public Template implements ITemoplate {} public Template2 implements ITemplate {} 我有一个接受类对象并实例化它的方法 public addTemplate(Class<ITemplate> template){ pipe.add(template.newInstance()) } 编译时错误:

我有一个接口和两个实现该接口的具体类

public interface ITemplate{}

public Template implements ITemoplate {}
public Template2 implements ITemplate {}
我有一个接受类对象并实例化它的方法

public addTemplate(Class<ITemplate> template){
    pipe.add(template.newInstance())
}
编译时错误:

我是否遗漏了什么,或者是否有解决方法?

Class
将严格接受
ITemplate.Class

Class尝试以下方法:

// works for all classes that inherit from ITemplate.
public addTemplate(Class< ? extends ITemplate> template){ 
    pipe.add(template.newInstance())
}
//适用于从ITemplate继承的所有类。
公共addTemplate(类<?扩展项目板>模板){
添加(template.newInstance())
}
而不是

// only accepts ITemplate Type Class (Strict Type).
public addTemplate(Class<ITemplate> template){ 
    pipe.add(template.newInstance())
}
//仅接受ITemplate类型类(严格类型)。
公共addTemplate(类模板){
添加(template.newInstance())
}
这里有一个解释:当您使用
Class
时,它是类
Itemplate
的严格类型。它永远不会接受除
ITemplate
之外的任何其他类型参数,因为它仅在编译时解析。 然而
// works for all classes that inherit from ITemplate.
public addTemplate(Class< ? extends ITemplate> template){ 
    pipe.add(template.newInstance())
}
// only accepts ITemplate Type Class (Strict Type).
public addTemplate(Class<ITemplate> template){ 
    pipe.add(template.newInstance())
}