我想从字符串生成一个对象,我也希望生成的对象是IObjectImpl类型,它扩展了IObject。
所以,我有一个工厂类方法,它接受一个字符串和一个接口类(比如扩展IObject的IObjectImpl.class,这是必需的)。该方法应该自动检测从string(使用反射)类型生成的对象是IObject并将其强制转换为IObjectImpl。
我已编写以下代码进行测试。但是,Intellij没有显示错误,同时在运行main方法的同时,我得到了最后显示的错误。
public <T extends IObject, E extends T> E getInstanceOfType(String clazz, Class type) {
try {
System.out.println("Type got is " + type);
return null;
} catch (Exception exception) {
throw new ObjectInstantiationException(String.format("Could not create the "
+ "instance of type %s", clazz), exception);
}
}
public static void main(String[] args) {
new Factory().getInstanceOfType("Some class", IObjectImpl.class);
}
错误是:
Error:(67, 49) java: ..path\Factory.java:67: incompatible types; inferred type argument(s) com.myCompany.IObject,java.lang.Object do not conform to bounds of type variable(s) T,E
found : <T,E>E
required: java.lang.Object
就检查类型而言,我只知道eClass.isAssignableFrom(tClass)方法。
我的最终目标是,我应该能够在没有任何演员的情况下调用IObjectImpl
中定义的方法。我怎么能用Java 1.6做到这一点?
答案 0 :(得分:3)
public class Factory {
public <T extends IObject, E extends T> E getInstanceOfType(String clazz, Class<E> type) {
try {
System.out.println("Type got is " + type);
return null;
} catch (Exception exception) {
throw new RuntimeException(String.format("Could not create the "
+ "instance of type %s", clazz), exception);
}
}
public static void main(String[] args) {
new Factory().<IObject, IObjectImpl>getInstanceOfType("Some class", IObjectImpl.class);
}
}
答案 1 :(得分:2)
您可以指定如下类型:(java 6)
public static void main(String[] args) {
new Factory().<IObject, IObjectImpl> getInstanceOfType("Some class", IObjectImpl.class);
}