我有一个 SimpleMapper
,它有一个以 ResultSet
作为参数的构造函数:
public abstract class SimpleMapper{
public SimpleMapper() {}
public SimpleMapper(ResultSet rs) {}
}
...我有几个来自 SimpleMapper
的子类。
现在我想编写一个泛型方法,将 ResultSet
转换为 List<T>
,其中 T
是 SimpleMapper
的子类。
代码如下:
public static <T extends SimpleMapper> List<T> resultSetToList(ResultSet rs, Class<? extends SimpleMapper> clazz) throws SQLException {
List<T> list = new ArrayList<>();
while (rs.next()) {
list.add(clazz.getConstructor(new Class[]{ResultSet.class}).newInstance(rs));
}
return list;
}
编译器给出了这个错误:
The method add(T) in the type List<T> is not applicable for the arguments (capture#2-of ? extends SimpleMapper)
我在这里做错了什么?我已将 T
指定为 SimlpeMapper
的子类。
答案 0 :(得分:3)
与其选择Class<? extends SimpleMapper>
,不如选择Class<T>
。这确保类的构造函数产生与您返回的列表类型相同的类型:
public static <T extends SimpleMapper> List<T> resultSetToList(ResultSet rs, Class<T> clazz)
throws SQLException {
try {
List<T> list = new ArrayList<>();
while (rs.next()) {
list.add(clazz.getConstructor(ResultSet.class).newInstance(rs));
}
return list;
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
// handle the exception in some way...
// maybe rethrow a RuntimeException?
throw new RuntimeException("Exception occurred during reflection!", e);
}
}