Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 270
WebDucer Avatar asked Dec 18 '13 09:12

WebDucer


2 Answers

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
    }
}
like image 99
André Stannek Avatar answered Sep 18 '22 22:09

André Stannek


Java uses type erasure so it is impossible to determine type of T at runtime.

like image 35
Paweł Adamski Avatar answered Sep 21 '22 22:09

Paweł Adamski