Unusual generic syntax: Arrays.<String>asList(...)
<typearg>methodname
is the syntax for explicitly specifying the type argument for a generic method
When you use a generic class, you usually have to specify the type argument (e.g. String
):
ArrayList<String> list = new ArrayList<String>();
With a generic method, you don't usually pass a type argument:
public static <T> void foo(T param) { }
...
String s = ...;
MyClass.foo(s);
You'll notice no where did we did the code explicitly specify we want the String
version of foo
, i.e. there was no explicit type argument <String>
specified like we saw when using a generic class (List<String>
).
The compiler is doing some compiler magic to infer the generic type argument based on context. This is a great thing and very powerful.
However, occassionally the compiler can't infer the type arguments automatically:
public static <T> void bar() { T myLocalVar = ...; ... }
MyClass.bar();
What concrete version of bar
are we trying to invoke, i.e. what is the type argument for this call? Well, the compiler doesn't either. We have to explicitly state the type argument, just like we normally do when using a generic class:
MyClass.<String>bar();
Also see:
- http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedMethods.html#FAQ002
- Lots of other good stuff there http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html
Aside: it may be worth mentioning that the Java 7 will be adding the so-called diamond operator to allow us to have the compiler to infer the type arguments when using generic classes now too:
ArrayList<String> list = new ArrayList<String>();
becomes
ArrayList<String> list = new ArrayList<>();
What is the point of the diamond operator (<>) in Java 7?
This is how you explicitly specify the type parameter to a generic method. In most cases, the compiler can infer it, but sometimes it needs to be explicitly stated.