【发布时间】:2017-01-17 11:19:30
【问题描述】:
我有一个有两个参数的方法:
public <P, T> T getT(P p, Class<T> returnType) {
//This method converts p to an instance of the type T.
}
或多或少,代码遍历returnType的所有setter并调用p上的getter方法:
T t = new T();
t.setBla(p.getBla());
现在,在遍历 T 类的所有 setter 时,我遇到了一个 Collection。我想为集合中的每个项目递归地调用它自己的方法。 我的问题是,我无法指定返回类型,因为我无法确定收到的 Collection 的返回类型。像这样的东西(没有反射的伪代码):
for(Object o : list) {
return getT(o, ???);
}
我尝试使用自定义注释来解决它,在该注释中我指定了该集合的 returnType,但我不能在我的注释中使用泛型:
public @interface ReturnType {
public Class<?> value();
}
所以我在 getT() 中的论点不匹配。如何在不更改 getT() 方法 (getT(P p, Class t)) 的泛型类型的情况下解决此问题?
【问题讨论】:
标签: java generics reflection