什么是运行时签名?

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)

来自Java Language Specification

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