Java generic methods in generics classes

‘for backwards compatibility’ seems a sufficient reason for the type erasure of class generic types – it is needed e.g. to allow you to return an untyped List and pass it to some legacy code. The extension of this to generic methods seems like a tricky sub-case.

The JLS snippet from 4.8 (which you quote) covers constructors, instance methods and member fields – generic methods are just a particular case of instance methods in general. So it seems your case is covered by this snippet.

Adapting JLS 4.8 to this specific case :

The type of a generic method is the raw type that corresponds to the
erasure of its type in the generic declaration corresponding to C.

(here the ‘type’ of the method would include all parameter and return types). If you interpret ‘erasure’ as ‘erasing all generics’, then this does seem to match the observed behaviour, although it is not very intuitive or even useful. It almost seems like an overzealous consistency, to erase all generics, rather than just generic class parameters (although who am I to second guess the designers).

Perhaps there could be problems where the class generic parameters interact with the method generic parameters – in your code they are fully independent, but you could imagine other cases where they are assigned / mixed together. I think it’s worth pointing out that use of raw types are not recommended, as per the JLS :

The use of raw types is allowed only as a concession to compatibility
of legacy code. The use of raw types in code written after the
introduction of genericity into the Java programming language is
strongly discouraged. It is possible that future versions of the Java
programming language will disallow the use of raw types

Some of the thinking of the java developers is apparent here :

http://bugs.sun.com/view_bug.do?bug_id=6400189

(bug + fix showing that a method’s return type is treated as part of the method’s type for the purposes of this type erasure)

There is also this request, where someone appears to request the behaviour you describe – only erase the class generic parameters, not other generics – but it was rejected with this reasoning:

The request is to modify type erasure so that in the type declaration Foo<T>, erasure only removes T from parameterized types. Then, it so happens that within Map<K,V>‘s declaration, Set<Map.Entry<K,V>> erases to Set<Map.Entry>.

But if Map<K,V> had a method that took type Map<String,V>, its erasure would just be Map<String>. For type erasure to change the number of type parameters is horrific, especially for compile-time method resolution. We are absolutely not going to accept this request.

It is too much to expect to be able to use raw types (Map) while still getting some of the type-safety of generics (Set<Map.Entry>).

Leave a Comment