在下面的代码中,当我打电话时,我getList()
无法指定<T>
. getList<T>()
不编译。
相反,我可能只打电话getList()
- 但那<T>
总是简单<Event>
的。
为什么是这样?
class Foo
{
public static void main (String[] args) throws java.lang.Exception
{
// For the sake of a complete example - the next method has
// my question.
Foo f = new Foo();
f.register(new Subscriber<MyEvent>() {
public void handle(MyEvent event){};
});
}
public <T extends Event> void register(Subscriber<T> subscriber) {
// Below won't work. I can't specify <T>, so getList()
// will return a HashSet<Subscriber<Event>>, to which I cannot
// add the Subscriber<T>!
getList().add(subscriber);
// Why can't I call getList<T>().add(subscriber) ?
}
private <T extends Event> HashSet<Subscriber<T>> getList() {
// For the sake of example, simply return a new HashSet.
return new HashSet<Subscriber<T>>();
}
}
interface Subscriber<T extends Event> {
public void handle(T event);
}
interface Event { }
class MyEvent implements Event { }