我正在尝试实现此方法,该方法接受数据库的行和列名称,并返回该单元格中的值。用户期望的类型由他们通过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
的具体类型方法返回编译器可接受的泛型类型。
关于如何做到这一点有什么想法吗?
最佳答案
您可以使用Class<T>
用户传入是为了让编译器相信代码的正确性,尽管它确实增加了额外的运行时强制转换的开销:
private <T> T getColumnByName(Row row, String name, Class<T> type) {
if (type == Long.class) {
return type.cast(row.getLong(name));
} else if (type == String.class) {
return type.cast(row.getString(name));
} ... continued...
}
关于java - 如何实现根据用户选择返回类型的Java函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55928898/