问题
I have a bit of a problem understanding Java's type erasure when it comes to bounded types. Consider this:
class Event {} // From the API
class FooEvent extends Event {}
abstract class Foo<EventType extends Event> {
public abstract <E extends EventType> void onEventCaught(E event);
}
class Bar extends Foo<FooEvent> {
@Override
public void onEventCaught(FooEvent event) {
}
}
Apparently this compiles without problems. The question that I ask myself is, for which parameter-types is Bar#onEventCaught() declared, here (as in, what does reflection think)?
Is it onEventCaught(FooEvent event) or maybe onEventCaught(Event event)?
回答1:
From the Java Language Specification
The erasure of a type variable (§4.4) is the erasure of its leftmost bound.
You have
<EventType extends Event>
and
<E extends EventType>
The leftmost bound of E is EventType, which is another type variable, whose leftmost bound is Event. So the erasure of E in
public abstract <E extends EventType> void onEventCaught(E event);
is Event.
Type variables do appear in .class files, and you can use them in reflection.
Class<?> clazz = Foo.class;
TypeVariable typeVariable = clazz.getTypeParameters()[0];
Type type = typeVariable.getBounds()[0];
System.out.println(typeVariable);
System.out.println(type);
prints
EventType
class com.example.Event
来源:https://stackoverflow.com/questions/28388034/what-will-be-the-runtime-signature