什么是运行时签名?
What will be the runtime signature?
关于有界类型,我对 Java 的类型擦除有一点理解。考虑一下:
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) {
}
}
显然这个编译没有问题。我问自己的问题是,Bar#onEventCaught()
在这里声明了哪些参数类型(例如,反射是怎么想的)?
是onEventCaught(FooEvent event)
还是onEventCaught(Event event)
?
The erasure of a type variable (§4.4) is the erasure of its leftmost bound.
你有
<EventType extends Event>
和
<E extends EventType>
E
的最左界是EventType
,这是另一种类型变量,其最左界是Event
。所以在
中擦除 E
public abstract <E extends EventType> void onEventCaught(E event);
是Event
。
类型变量确实出现在 .class
个文件中,您可以在反射中使用它们。
Class<?> clazz = Foo.class;
TypeVariable typeVariable = clazz.getTypeParameters()[0];
Type type = typeVariable.getBounds()[0];
System.out.println(typeVariable);
System.out.println(type);
打印
EventType
class com.example.Event
关于有界类型,我对 Java 的类型擦除有一点理解。考虑一下:
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) {
}
}
显然这个编译没有问题。我问自己的问题是,Bar#onEventCaught()
在这里声明了哪些参数类型(例如,反射是怎么想的)?
是onEventCaught(FooEvent event)
还是onEventCaught(Event event)
?
The erasure of a type variable (§4.4) is the erasure of its leftmost bound.
你有
<EventType extends Event>
和
<E extends EventType>
E
的最左界是EventType
,这是另一种类型变量,其最左界是Event
。所以在
E
public abstract <E extends EventType> void onEventCaught(E event);
是Event
。
类型变量确实出现在 .class
个文件中,您可以在反射中使用它们。
Class<?> clazz = Foo.class;
TypeVariable typeVariable = clazz.getTypeParameters()[0];
Type type = typeVariable.getBounds()[0];
System.out.println(typeVariable);
System.out.println(type);
打印
EventType
class com.example.Event