开发者

Java Generics - Check type of T

I am using a method like this

private static <T> void setPreference(String key, T value)
{
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Controller.getContext());

    SharedPreferences.Editor editor = prefs.edit();

    editor.putString(key, value.toString());

    editor.commit();
}

Unfortunately, putString is one of multiple put methods. I also want to use putBoolean and putInt. My problem is that I want to support the specific types (I don't want to save everything as a string like I am doing), and I want to reduce code duplication as much as possible. I'm used to C# where this kind of thing is very easy, so I feel like I'm missing something obvious.开发者_JAVA百科


Make several overloads: one that accepts <T extends Boolean>, etc, for each of the specific types you want to carve out.


You can use if (value instanceof Boolean) { editor.putBoolean(..); }.

But that's not quite OO. What you can do is move the responsibility to the value object:

public intarface ValueHolder<T> {
     void putInEditor(String key, Editor editor);
     T getValue();
}

public class StringValueHolder extends ValueHolder<String> {
    private String value;
    // constructor here to initialize the value
    public putInEditor(String key, Editor editor) {
        editor.putString(key, value);
    }

    public String getValue() {
         return value;
    }
}

public class BooleanValueHolder extends ValueHolder<Boolean> {
    private Boolean value;
    // constructor here to initialize the value
    public putInEditor(String key, Editor editor) {
        editor.putBoolean(key, value);
    }

    public Boolean getValue() {
         return value;
    }
}

It's more verbose, I agree, so If you don't want to complicate things, stick with the instanceof solution.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜