By nirkov


2019-10-14 22:09:40 8 Comments

I'm trying to do casting by Type to Object at runtime but it doesn't work in that way. There is some smart way to do that instead of using instanceOf() for all options?

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});
}

1 comments

@Erwin Bolwidt 2019-10-14 22:47:22

The approach that you show (using Class.cast) does work, but has the overhead of handling an exception.

A clearer and more concise way of doing this is using the Class.isInstance method:

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?
    }
}

@nirkov 2019-10-15 08:43:31

It doesn't work also. I get an error from 'put': "cannot resolve method 'put(java.lang.String, T)'

Related Questions

Sponsored Content

24 Answered Questions

[SOLVED] Get generic type of class at runtime

27 Answered Questions

[SOLVED] How to cast int to enum?

  • 2008-08-27 03:58:21
  • lomaxx
  • 1271728 View
  • 2998 Score
  • 27 Answer
  • Tags:   c# enums casting

3 Answered Questions

[SOLVED] Cast object to interface in TypeScript

16 Answered Questions

[SOLVED] SQLite in Android How to update a specific row

18 Answered Questions

[SOLVED] How to cast an Object to an int

2 Answered Questions

1 Answered Questions

[SOLVED] How to cast object to type known only at runtime

1 Answered Questions

[SOLVED] Check if object is cast to its dynamic type in Java

  • 2017-03-10 03:46:11
  • Kröw
  • 560 View
  • 0 Score
  • 1 Answer
  • Tags:   java casting

1 Answered Questions

Sponsored Content