How do I cast from int to generic type Integer?
- by Rob Kent
I'm relatively new to Java and am used to generics in C# so have struggled a bit with this code. Basically I want a generic method for getting a stored Android preference by key and this code, albeit ugly, works for a Boolean but not an Integer, when it blows up with a ClassCastException. Can anyone tell me why this is wrong and maybe help me improve the whole routine (using wildcards?)?
public static <T> T getPreference(Class<T> argType, String prefKey, T defaultValue,
SharedPreferences sharedPreferences) {
...
try {
if (argType == Boolean.class) {
Boolean def = (Boolean) defaultValue;
return argType.cast(sharedPreferences.getBoolean(prefKey, def));
} else if (argType == Integer.class) {
Integer def = (Integer) defaultValue;
return argType.cast(sharedPreferences.getInt(prefKey, def));
} else {
AppGlobal.logWarning("getPreference: Unknown type '%s' for preference '%s'. Returning default value.",
argType.getName(), prefKey);
return defaultValue;
}
} catch (ClassCastException e) {
AppGlobal.logError("Cast exception when reading pref %s. Using default value.", prefKey);
return defaultValue;
}
}
I've tried various ways - using the native int, casting to an Integer, but nothing works.