我想要下面这样的东西(示例我将如何在 C# 中执行此操作),以从 SQLiteDB 获取类型值:
private T GetValueFromDB<T>(String colName) {
object returnValue = null;
switch (typeof(T)) {
case Boolean:
returnValue = dbData.getInt(colName) == 1;
break;
case Int32:
returnValue = dbData.getInt(colName);
break;
case Int64:
returnValue = dbData.getLong(colName);
break;
case String:
returnValue = dbData.getString(colName);
break;
}
return (T)returnValue;
}
是否有可能(使用 switch case 或 if else)在 Java 中实现它?
最佳答案
如果你在调用方法时已经知道类型,你可以这样做:
private T GetValueFromDB<T>(String colName, Class<T> returnType) {
if(returnType.equals(Boolean.class)) {
return (T)(dbData.getInt(colName) == 1);
} else if(returnType.equals(Int32.class)) {
// and so on
}
}
关于Java泛型方法通过使用类型开关获取类型值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20653606/