Search code examples
javagenericsmethodsswitch-statementtypeof

Java generic method to get value of type by using switch on type


I want to have something like this below (example how I would do this in C#), to get typed value from 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;
}

Is there a possibility (with switch case or if else) to implement it in Java?


Solution

  • If you already know the type when calling the method, you could do something like this:

    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
        }
    }