[英]Is it possible to have an indefinite number of type parameters in Java?
I'm making an event system in Java and I've run into a problem in writing the Listener part. 我正在用Java开发事件系统,在编写侦听器部分时遇到了问题。
This is my current Listener
class: 这是我当前的
Listener
类:
public interface Listener<E extends Event<?>> {
public void handleEvent(E event);
}
I want to keep it expandable in a way that I can have one Listener class that can be flexible to any Event type, ie Listener<Foo>
and Listener<Bar>
instead of FooListener
and BarListener
, but I also want implementing classes to be able to listen to multiple events. 我想让它保持可扩展性,以便我可以拥有一个对任何事件类型都可以灵活使用的侦听器类,即
Listener<Foo>
和Listener<Bar>
而不是FooListener
和BarListener
,但我也希望实现类能够听多个事件。
My problem is that a class cannot implement the Listener class with two different type parameters. 我的问题是,一个类无法使用两个不同的类型参数来实现Listener类。
public class MultiListener implements Listener<Foo>, Listener<Bar> {
// does not work
}
I know it's possible for a method to have an indefinite number of parameters, like this: 我知道一种方法可能具有不确定数量的参数,如下所示:
public void toInfinityAndBeyond(String... lotsOfStrings) {
}
But can my Listener
class have an indefinite number of type parameters to listen to multiple events? 但是我的
Listener
类是否可以具有无限数量的类型参数来侦听多个事件?
public class MultiListener implements Listener<ThisEvent, ThatEvent, AnotherEvent> {
// hypothetical
}
The problem is that Listener<Foo>
and Listener<Bar>
are really the exact same interface, due to generic type erasure . 问题在于,由于泛型类型擦除 ,
Listener<Foo>
和Listener<Bar>
实际上是完全相同的接口。 So this isn't possible (AFAIK). 因此,这是不可能的(AFAIK)。
I don't fully understand generics, but I've found they tend to make Java, a statically typed language, a lot more static. 我不完全理解泛型,但是我发现它们倾向于使Java(一种静态类型的语言)更加静态。 This can be a good thing.
这可能是一件好事。 But what you are trying to do is rather dynamic.
但是您想要做的是相当动态的。
So in this case I would dump the generics. 因此,在这种情况下,我将转储泛型。 Make Foo and Bar extend or implement Event.
使Foo和Bar扩展或实现Event。 (Event with no "<>".) Make sure the Event class has enough methods that the code in Listener's handleEvent() doesn't need multiple
if
's using instanceof
; (事件没有“<>”),确保事件类有足够的方法是,在监听器的handleEvent()的代码并不需要多
if
的使用instanceof
; so it can just deal with plain Event objects. 因此它只能处理简单的Event对象。 (Mind, the occasional
instanceof
won't hurt anything, usually.) (请注意,偶尔的
instanceof
不会伤害任何东西。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.