我觉得这完全莫名其妙。出于某种原因,javac 似乎以未指定的泛型对待引用,并且<?>
在类型安全方面有所不同。有谁知道这是为什么(Java 1.6)?
public abstract class ClassWithGenericMember<GenMember> {
GenMember getMember() {
return (GenMember) null;
}
<GenReturn> GenReturn handle(Handler<GenReturn> handler) {
return handler.handle();
}
interface Handler<GenHandled> {
public GenHandled handle();
}
static class ClassWithMember extends ClassWithGenericMember<MemberType> {
}
static class MemberType {
}
static class HandledType {
}
public static void main(String[] argv) {
HandledType handled = null;
Handler<HandledType> handler = new Handler<HandledType>(){
public HandledType handle() {
return (HandledType) null;
}
};
ClassWithMember concrete = new ClassWithMember();
ClassWithGenericMember<?> bracket = concrete;
ClassWithGenericMember noBracket = concrete;
handled = concrete.handle(handler); //compiles
handled = bracket.handle(handler); //compiles
handled = noBracket.handle(handler); //fails:
/*
ClassWithGenericMember.java:38: incompatible types
found : java.lang.Object
required: ClassWithGenericMember.HandledType
handled = noBracket.handle(handler);
^
Note: ClassWithGenericMember.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
*/
}
}