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.
The reason for this is backwards compatibility with pre-generics code. The pre-generics code did not use generic arguments, instead using what seems today to be a raw type. The pre-generics code would use
Object
references instead of references using the generic type, and raw types use typeObject
for all generic arguments, so the code was indeed backwards compatible.As an example, consider this code:
This is pre-generic code, and once generics were introduced, this was interpreted as a raw generic type equivalent to:
Because the ? doesn't have an
extends
orsuper
keyword after it, it is transformed into this:The version of
List
that was used before generics used anObject
to refer to a list element, and this version also uses anObject
to refer to a list element, so backwards compatibility is retained.'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 :
(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 :
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:
With Java Generics, if you use the raw form of a generic class, then all generics on the class, even unrelated generic methods such as your
makeSingletonList
anddoSomething
methods, become raw. The reason as I understand it is to provide backwards compatibility with Java code written pre-generics.If there is no use for your generic type parameter
T
, then simply remove it fromMyGenericClass
, leaving your methods generic withK
. Else you'll have to live with the fact that the class type parameterT
must be given to your class to use generics on anything else in the class.I've found one reason to fully discard generics (however it's not quite good). Reason is: generics may be bounded. Consider this class:
The compiler has to discard generics in
doSomething
, when you use the class without generics. And I think all generics are discarded to be consistent with this behavior.makeSingletonList
compiles because Java does an unchecked cast fromList
toList<K>
(however compiler displays warning).This doesn't answer the fundamental question, but does address the issue of why
makeSingletonList(...)
compiles whilstdoSomething(...)
does not:In an untyped implementation of
MyGenericClass
:...is equivalent to:
This will compile (with several warnings), but is then open to runtime errors.
Indeed, this is also analogous to:
...which compiles but will throw a runtime
ClassCastException
when you try and get theString
value out and cast it to anInteger
.From my comment on MAnyKeys answer:
I think the full type erasure makes sense combined with the mentioned backwards compatability. When the object is created without generic type arguments it can be (or shoudl be?) assumed that the usage of the object takes place in non generic code.
Consider this legacy code:
called like this:
Now the class and it's method are made generic:
Now the above caller code wouldn't compile anymore as
NotKType
is not a suptype ofKType
. To avoid this the generic types are replaced withObject
. Although there are cases where it wouldn't make any difference (like your example), it is at least very complex for the compiler to analyze when. Might even be impossible.I know this szenario seems a little constructed but I'm sure it happens from time to time.