Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/366.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_Reflection - Fatal编程技术网

Java 作为参数实现接口的反射类

Java 作为参数实现接口的反射类,java,reflection,Java,Reflection,我想将一个类作为参数传递,并返回该类的一个实例。我需要确保类实现接口。我知道我可以通过反思来做到: Object get(Class theClass) { return theClass.newInstance(); } 我不知道的是如何确保类实现接口 ISomeInterface get(Class<? extends ISomeInterface> theClass) {...} // errrr... you know what i mean? 接口获取(类在此处

我想将一个
类作为参数传递,并返回该类的一个实例。我需要确保类实现
接口
。我知道我可以通过反思来做到:

Object get(Class theClass) {
    return theClass.newInstance();
}
我不知道的是如何确保类实现接口

ISomeInterface get(Class<? extends ISomeInterface> theClass) {...}
// errrr... you know what i mean?

接口获取(类在此处查看

在此处查看

使用
isAssignableFrom

ISomeInterface get(Class<? extends ISomeInterface> theClass) {
    if (ISomeInterface.class.isAssignableFrom(theClass)) {
        return theClass.newInstance();
    } else { /* throw exception or whatever */ }
}

接口获取(类使用
isAssignableFrom

ISomeInterface get(Class<? extends ISomeInterface> theClass) {
    if (ISomeInterface.class.isAssignableFrom(theClass)) {
        return theClass.newInstance();
    } else { /* throw exception or whatever */ }
}

ISomeInterface get(Class您必须显式检查给定的类对象是否不是接口。
isAssignableFrom()将返回true,即使您拥有接口的两个类对象。由于它们位于同一层次结构上,它将返回true

我建议您尝试以下代码

ISomeInterface get(Class<? extends ISomeInterface> theClass) {
if(!clazz.isInterface()){
    if (ISomeInterface.class.isAssignableFrom(theClass)) {
        return theClass.newInstance();
    } else { /* throw exception or whatever */ }
}
}

ISomeInterface get(Class您必须显式检查给定的类对象是否不是接口。
isAssignableFrom()将返回true,即使您拥有接口的两个类对象。由于它们位于同一层次结构上,它将返回true

我建议您尝试以下代码

ISomeInterface get(Class<? extends ISomeInterface> theClass) {
if(!clazz.isInterface()){
    if (ISomeInterface.class.isAssignableFrom(theClass)) {
        return theClass.newInstance();
    } else { /* throw exception or whatever */ }
}
}
ISomeInterface get(类您可以使用泛型:

public <T extends ISomeInterface> T get(Class<T> theClass) {
   return theClass.newInstance();
}
public T get(类中的类){
返回class.newInstance();
}
您可以使用泛型:

public <T extends ISomeInterface> T get(Class<T> theClass) {
   return theClass.newInstance();
}
public T get(类中的类){
返回class.newInstance();
}