使用以下代码行:
List<Dao<?>> genericList = Dao.get(Person.class, q);
我调用以下静态方法:
/**
* Dynamically create list of generic Dao's
* @param className
* @return
*/
public static List<Dao<?>> get(Class<?> classType, Query q){
List<Dao<?>> list = new ArrayList<>();
try {
List<Map<String, Object>> results = Model.getAll(q);
for (Map<String, Object> map : results) {
Dao<?> obj = PojoFactory.createPojo(classType.getSimpleName());
for (String key : map.keySet()) {
//Double check if field names exist before setting them
//http://commons.apache.org/proper/commons-beanutils/
BeanUtils.setProperty(obj, key, map.get(key));
}
list.add(obj);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return list;
}
我想要返回正确的类型,而不是返回DAO类型,以便我不需要在之后进行投射。
为了做到这一点,我需要能够扭转:
Person.class
适应这条线:
List<Dao<?>> genericList = Dao.get(Person.class, q);
到正确的类型,以便我可以像这样调用它:
List<Person> genericList = Dao.get(Person.class, q);
有什么想法吗?
答案 0 :(得分:0)
您应该在方法标题中引入一个类型参数。
public static <T extends Dao<T>> List<T> get(Class<T> classType, Query q){
List<T> list = new ArrayList<>();
try {
List<Map<String, Object>> results = Model.getAll(q);
for (Map<String, Object> map : results) {
T obj = (T) PojoFactory.createPojo(classType.getSimpleName());
for (String key : map.keySet()) {
//Double check if field names exist before setting them
//http://commons.apache.org/proper/commons-beanutils/
BeanUtils.setProperty(obj, key, map.get(key));
}
list.add(obj);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return list;
}
我假设Person的定义如下:
class Person extends Dao<Person> {
}