我想按类类型检索实例。但现在我正在与泛型作斗争。我的代码不起作用,我也不知道为什么。这是:
public class Main {
public static void main(String[] args) throws Exception {
Provider provider = new Provider("prop");
AbstractHolder obj = provider.create(DefaultHolder.class);
System.out.println(obj.getProperty());
}
}
具有损坏的 create
方法的提供程序类
public class Provider {
private String property;
public Provider(String property) {
this.property = property;
}
public <T> create (Class<T> type) throws Exception {
return type.getConstructor(String.class).newInstance(property);
}
}
这是我的 Holder impl。
public class DefaultHolder extends AbstractHolder {
public DefaultHolder(String field) {
super(field);
}
}
和AbstractHolder抽象类。
public abstract class AbstractHolder {
private String property;
public AbstractHolder(String property) {
this.property = property;
}
public String getProperty() {
return property;
}
}
有什么想法可以修复我的 Provider 类中的泛型吗?
附注
问题出在这个方法
public <T> create (Class<T> type) throws Exception {
return type.getConstructor(String.class).newInstance(property);
}
最佳答案
试试这个:
public class Main {
public static void main(String[] args) throws Exception {
Provider provider = new Provider("prop");
AbstractHolder obj = provider.create(DefaultHolder.class);
System.out.println(obj.getProperty());
}
}
public class Provider {
private String property;
public Provider(String property) {
this.property = property;
}
public <T extends AbstractHolder> T create(Class<T> type) throws InstantiationException, IllegalAccessException, IllegalArgumentException, SecurityException, InvocationTargetException, NoSuchMethodException {
return type.getConstructor(property.getClass()).newInstance(property);
}
}
关于java - 如何使用 Reflection API 正确泛化返回实例的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24605960/