Combining Raw Types and Generic Methods

It’s not exactly what you’d expect, but if you refer to a generic class in raw form, you lose the ability to use generics in any way for instance members. It’s not restricted to generic methods either, check out this:

 public class MyContainer<T> {

     public List<String> strings() {
         return Arrays.asList("a", "b");
     }
 }

 MyContainer container = new MyContainer<Integer>();
 List<String> strings = container.strings(); //gives unchecked warning!

This is the relevant part of the JLS (4.8):

The type of a constructor (§8.8), instance method (§8.4, §9.4), or non-static field (§8.3) M of a raw type C that is not inherited from its superclasses or superinterfaces is the raw type that corresponds to the erasure of its type in the generic declaration corresponding to C.

Leave a Comment