What will be the runtime signature?

隐身守侯 提交于 2020-01-04 14:21:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!