简体   繁体   中英

Check type of object in generic function android java

I have a function in my android application:

public static <T> void saveLocalData(Context context, String key, Class<T> value) {
    // Check type of value here
    SharedPreferences prefs = context.getSharedPreferences(
            Constants.PREFERENCES_KEY, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    if(value.isAssignableFrom(String.class)){
        //Put value here
    }
    else if(value.isAssignableFrom(Boolean.class)){
        //Put value here            
    }

    editor.commit();
}

I want to check type of value in this function (I want to check two type Boolean and String ), but I don't know how to do it! Can anyone give any suggestion? Thanks!

Thanks every for help! 谢谢大家的帮助! I have one more problem that is how to save it value to Preferences ?

You could use Class.isAssignableFrom() .

Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter


UPDATE : By the edit in the question, and in order to set the key/value in a SharedPreferences.Editor , use putString() and putBoolean() .

Take into account you'll need to receive the value as an argument. Notice that if you receive the value, you can already access its class (so you don't need Class<T> as an argument nor isAssignableFrom() ), and check it by means of the instanceof operator:

public static <T> void saveLocalData(Context context, String key, T value) {
    SharedPreferences prefs = context.getSharedPreferences(
        Constants.PREFERENCES_KEY, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    if (value instanceof String) { 
        editor.putString(key, (String) value);
    }
    else if (value instanceof Boolean){
        editor.putBoolean(key, (Boolean) value);
    }
    editor.commit();
}

I haven't tried it on Android, but since it's syntax is usually equivalent to Java, here's two ways to do it in Java:

if (Boolean.class.equals(value) || String.class.equals(value)) {
    // Do stuff.
}

This works because Boolean and String are both final and you don't have to worry about extended classes. I think you could even use == in this case (assuming a normal ClassLoader ) as typically there's only one instance of Class per Class on the classpath. If you need to worry about extending classes, use:

if (Boolean.class.isAssignableFrom(value) || String.class.isAssignableFrom(value)) {
    // Do stuff.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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