Preface: I understand generics and how they're declared at the class level (e.g. class MyClass<T>
) but I've never seen it declared at the level of a static method, and without any explicit bindings (e.g. class MySubclass<String> extends MyClass
).
I found this code snippet in an app I'm working on (I didn't write this part). I've never seen a method declared this way. <T>
is not defined anywhere else in the class. Intent.getExtras().get()
returns an Object
which may actually be a String
, Boolean
...etc.
private static <T> T getItemExtra(final Intent intent, final String extraName) {
T item = null;
if(intent != null && intent.getExtras() != null) {
item = (T) intent.getExtras().get(extraName);
}
return item;
}
Sample usage:
String s1 = getItemExtra(someIntent, "some_string_extra");
Uri u1 = getItemExtra(someIntent, "some_uri_extra");
How does the JVM know what type to use for <T>
? (Yes this method compiles and executes successfully).