[英]Generic method return generic type
我有一個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
子類。
而不是Class<? extends SimpleMapper>
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.