Подход, который вы показываете (используя Class.cast
), работает, но требует дополнительных усилий для обработки исключения.
Более ясный и краткий способ сделать это - использоватьClass.isInstance
метод:
public <T> void updateUser(final SQLiteDatabase db, final String key, Class<T> cls, Object newVal, String prevVal){
ContentValues userValue = new ContentValues();
if (cls.isInstance(newVal)) {
// cls.cast is only necessary if `userValue` has a value type of T
// like "Map<String, T> userValue"; if it's "Map<String, Object>" then
// you can just use "newVal" without the cast.
userValue.put(key, cls.cast(newVal));
// You'll want to include "db.update" in the "if"-block,
// since you need to update at least one field to make it a
// valid SQL statement.
db.update(mDBName, userValue, key + " = ?", new String[] {prevVal});
} else {
// Raise some kind of error or log something?
}
}