我正在尝试实现这个接受数据库行和列名的方法,它返回该单元格中的值。用户期望的类型由他们通过Class<T> type.
// This return T, the value under the columnName in the row.
public <T> T getColumnByName(Row row, String columnName, Class<T> type)
而且我可以访问这个名为的对象Row,它方便地为我提供了以下方法:
row.getString(String columnName) // Gets String stored under column
row.getLong(String columnName) // Gets the Long stored under column
etc...
所以这是非常基本的,但我对泛型有点卡住了。我试图以getColumnByName这种方式实现:
private <T> T getColumnByName(Row row, String name, Class<T> type) {
if (type == Long.class) {
return row.getLong(name);
} else if (type == String.class) {
return row.getString(name);
} ... continued...
}
但是,我收到错误“不兼容的类型,必需:T,找到:long”。我不确定如何处理将Row方法返回的具体类型转换为编译器将接受的泛型类型。
关于如何做到这一点的任何想法?
慕斯709654
相关分类