Android code - the SharedPreferences class exports different methods for persisting/retrieving different preferences :
@SuppressWarnings(\"unchecked\")
public st
The normal way is to use the Class.cast(obj), biut you will need an instance of the T Class, this is typically done by passing one in to the method, but in your case will be fine:
return Boolean.class.cast(pregs.getBoolean(key, (Boolean)defaultValue));
EDIT: After the comment, yes, it could be a problem with the type mismatch.
You will need to pass in the class type as part of your method, or infer it from the default value (if it is not null:
return defaultValue.getClass().cast(pregs.getBoolean(key, (Boolean)defaultValue));
Editing again with working example (this works wihtout any warnings for me):
public class JunkA {
private boolean getBoolean(String key, boolean def) {
return def;
}
private float getFloat(String key, float def) {
return def;
}
private String getString(String key, String def) {
return def;
}
private int getInt(String key, int def) {
return def;
}
public T getProperty(final Class clazz, final String key,
final T defval) {
if (clazz.isAssignableFrom(Boolean.class)) {
return clazz.cast(getBoolean(key, (Boolean) defval));
}
if (clazz.isAssignableFrom(String.class)) {
return clazz.cast(getString(key, (String) defval));
}
if (clazz.isAssignableFrom(Boolean.class)) {
return clazz.cast(getFloat(key, (Float) defval));
}
if (clazz.isAssignableFrom(Integer.class)) {
return clazz.cast(getInt(key, (Integer) defval));
}
return defval;
}
}