我正在尝试在运行时按类型将其强制转换为对象,但这种方式不起作用。
有什么聪明的方法可以代替所有选项使用instanceOf()
?
public <T> void updateUser(final SQLiteDatabase db, final String key, Class<T> cls, Object newVal, String prevVal){
ContentValues userValue = new ContentValues();
try {
userValue.put(key, cls.cast(newVal));
} catch(ClassCastException e) {
}
db.update(mDBName, userValue, key + " = ?", new String[] {prevVal});
}
答案 0 :(得分:0)
您展示的方法(使用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?
}
}