I have a Interface IEvent that looks like this:
我有一个看起来像这样的接口IEvent:
public abstract interface IEvent<T> {
public abstract void handleEvent(T payload);
}
and 2 Interfaces with a concrete generic type that looks like this:
和2具有如下所示的具体泛型类型的接口:
public interface IKeyDownEvent extends IEvent<KeyDownEventPayload> {}
public interface IKeyUpEvent extends IEvent<KeyUpEventPayload> {}
Both KeyUpEvent and KeyDownEvent are extending from EventPayload.
KeyUpEvent和KeyDownEvent都是从EventPayload扩展而来的。
How do I go about and iterate over a ArrayDeque and only call handleEvent() for classes that implement IKeyDownEvent but not for example IKeyUpEvent?
如何对ArrayDeque进行迭代并迭代,只为实现IKeyDownEvent的类调用handleEvent(),而不是例如IKeyUpEvent?
I tried this but it seem to not work:
我试过这个,但它似乎不起作用:
if (payload.getClass() == ev.getClass().getGenericSuperclass())
ev.handleEvent(payload);
1 个解决方案
#1
1
To literally answer your question, use Class.getGenericInterfaces
instead of Class.getGenericSuperclass
as IEvent
is an immediately super interface and not an immediate superclass. Or arguably better particularly now we don't have interface interface
, make IEvent
an abstract class.
要从字面上回答你的问题,使用Class.getGenericInterfaces而不是Class.getGenericSuperclass,因为IEvent是一个直接的超级接口,而不是一个直接的超类。或者可以说更好,特别是现在我们没有接口接口,使IEvent成为一个抽象类。
Still that very fragile. Only checking the immediate types, for instance. Also checking runtime types is such a bad idea.
仍然非常脆弱。例如,仅检查直接类型。检查运行时类型也是一个坏主意。
Better, don't put the IEvent
straight in to the Deque
. Wrap IKeyDownEvent
in a class that deals with KeyDownEventPayload
correctly, and similarly for other types.
更好的是,不要把IEvent直接放到Deque中。将IKeyDownEvent包装在正确处理KeyDownEventPayload的类中,对其他类型也是如此。
#1
1
To literally answer your question, use Class.getGenericInterfaces
instead of Class.getGenericSuperclass
as IEvent
is an immediately super interface and not an immediate superclass. Or arguably better particularly now we don't have interface interface
, make IEvent
an abstract class.
要从字面上回答你的问题,使用Class.getGenericInterfaces而不是Class.getGenericSuperclass,因为IEvent是一个直接的超级接口,而不是一个直接的超类。或者可以说更好,特别是现在我们没有接口接口,使IEvent成为一个抽象类。
Still that very fragile. Only checking the immediate types, for instance. Also checking runtime types is such a bad idea.
仍然非常脆弱。例如,仅检查直接类型。检查运行时类型也是一个坏主意。
Better, don't put the IEvent
straight in to the Deque
. Wrap IKeyDownEvent
in a class that deals with KeyDownEventPayload
correctly, and similarly for other types.
更好的是,不要把IEvent直接放到Deque中。将IKeyDownEvent包装在正确处理KeyDownEventPayload的类中,对其他类型也是如此。