Java Generics: Generic type defined as return type only
The method returns a type of whatever you expect it to be (<X>
is defined in the method and is absolutely unbounded).
This is very, very dangerous as no provision is made that the return type actually matches the returned value.
The only advantage this has is that you don't have to cast the return value of such generic lookup methods that can return any type.
I'd say: use such constructs with care, because you lose pretty much all type-safety and gain only that you don't have to write an explicit cast at each call to get()
.
And yes: this pretty much is black magic that blows up at runtime and breaks the entire idea of what generics should achieve.
The type is declared on the method. That's that "<X>
" means. The type is scoped then to just the method and is relevant to a particular call. The reason your test code compiles is that the compiler tries to determine the type and will complain only if it can't. There are cases where you have to be explicit.
For example, the declaration for Collections.emptySet()
is
public static final <T> Set<T> emptySet()
In this case, the compiler can guess:
Set<String> s = Collections.emptySet();
But if it can't, you must type:
Collections.<String>emptySet();