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.

Leave a Comment