Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics - Check type of T

Tags:

java

generics

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.

like image 523
Josh Avatar asked Dec 28 '22 21:12

Josh


1 Answers

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

like image 143
bmargulies Avatar answered Jan 10 '23 19:01

bmargulies