简体   繁体   English

如何将 object 转换为仅在运行时已知的类型?

[英]How to cast object to type known only at runtime?

I'm trying to do casting by Type to Object at runtime but it doesn't work in that way.我正在尝试在运行时按类型转换为 Object ,但它不能以这种方式工作。 There is some smart way to do that instead of using instanceOf() for all options?有一些聪明的方法可以做到这一点,而不是对所有选项都使用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});
}

The approach that you show (using Class.cast ) does work, but has the overhead of handling an exception.您展示的方法(使用Class.cast )确实有效,但有处理异常的开销。

A clearer and more concise way of doing this is using the Class.isInstance method:一种更清晰、更简洁的方法是使用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?
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM