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(new Integer(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;
}
}
My calling code is:
mAccuracy = GlobalPreferences.getPreference(Integer.class, prefKey, mAccuracy, sharedPreferences);
Here is the Android code for getInt():
public int getInt(String key, int defValue) {
synchronized (this) {
Integer v = (Integer)mMap.get(key);
return v != null ? v : defValue;
}
}
I've tried various ways - using the native int, casting to an Integer, but nothing works.