Kingfisher Phuoc
Kingfisher Phuoc

Reputation: 8190

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!

Edited: Thanks every for help! I have one more problem that is how to save it value to Preferences?

Upvotes: 4

Views: 5412

Answers (2)

Xavi L&#243;pez
Xavi L&#243;pez

Reputation: 27880

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

Upvotes: 5

Vala
Vala

Reputation: 5674

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

Upvotes: 1

Related Questions