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