Search code examples
javagenericslanguage-designgeneric-methodraw-types

Java generic methods in generics classes


If you create a generic class in Java (the class has generic type parameters), can you use generic methods (the method takes generic type parameters)?

Consider the following example:

public class MyClass {
  public <K> K doSomething(K k){
    return k;
  }
}

public class MyGenericClass<T> {
  public <K> K doSomething(K k){
    return k;
  }

  public <K> List<K> makeSingletonList(K k){
    return Collections.singletonList(k);
  }
}

As you would expect with a generic method, I can call doSomething(K) on instances of MyClass with any object:

MyClass clazz = new MyClass();
String string = clazz.doSomething("String");
Integer integer = clazz.doSomething(1);

However, if I try to use instances of MyGenericClass without specifying a generic type, I calling doSomething(K) returns an Object, regardless of what K was passed in:

MyGenericClass untyped = new MyGenericClass();
// this doesn't compile - "Incompatible types. Required: String, Found: Object"
String string = untyped.doSomething("String");

Oddly, it will compile if the return type is a generic class - e.g. List<K> (Actually, this can be explained - see answer below):

MyGenericClass untyped = new MyGenericClass();
List<String> list = untyped.makeSingletonList("String"); // this compiles

Also, it will compile if the generic class is typed, even if only with wildcards:

MyGenericClass<?> wildcard = new MyGenericClass();
String string = wildcard.doSomething("String"); // this compiles
  • Is there a good reason why calling a generic method in an untyped generic class shouldn't work?

  • Is there some clever trick relating to generic classes and generic methods that I am missing?

EDIT:

To clarify, I would expect an untyped or raw-typed generic class not to honour the generic class's type parameters (because they haven't been provided). However, it's not clear to my why an untyped or raw-typed generic class would mean that generic methods are not honoured.

It transpires that this issue has already been raised on SO, c.f. this question. The answers to this explain that when a class is untyped / in its raw-form, all generics are removed from the class - including typing of generic methods.

However, there isn't really an explanation as to why this is the case. So allow me to clarify my question:

  • Why does Java remove generic method typing on untyped or raw-type generic classes? Is there a good reason for this, or was it just an oversight?

EDIT - discussion of JLS:

It has been suggested (in answer to the previous SO question and to this question) that this is treated in JLS 4.8, which states:

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.

It is clear to me how this relates to an untyped class - the class generic types are replaced with the erasure types. If the class generics are bound, then the erasure type corresponds to those bounds. If the they are not bound, then the erasure type is Object - e.g.

// unbound class types
public class MyGenericClass<T> {
  public T doSomething(T t) { return t; }
}
MyGenericClass untyped = new MyGenericClass();
Object t = untyped.doSomething("String");

// bound class types
public class MyBoundedGenericClass<T extends Number> {
  public T doSomething(T t) { return t; }
}
MyBoundedGenericClass bounded = new MyBoundedGenericClass();
Object t1 = bounded.doSomething("String"); // does not compile
Number t2 = bounded.doSomething(1); // does compile

Whilst generic methods are instance methods, it is not clear to me that JLS 4.8 applies to generic methods. The generic method's type (<K> in earlier example) is not untyped, as it's type is determined by the method parameters - only the class is untyped / raw-typed.


Solution

  • '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 :

    https://bugs.java.com/bugdatabase/view_bug?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>).