In the Google Guava EventBusExplained page, I don’t understand when they say the following:
To listen for a common event supertype (such as EventObject or
Object)…
…in traditional Java events: not easy.
…with EventBus:
events are automatically dispatched to listeners of any supertype,
allowing listeners for interface types or “wildcard listeners” for
Object.
- What does it mean to listen for a common event supertype?
- When they mention EventObject , are they talking about java.util.EventObject?
- What does it mean to allow “listeners for interface types or “wildcard listeners” for Object”?
This has to do with the limitations of method-overloading and interfaces that Guava’s
EventBusclass can overcome.For interfaces, consider the following scenario:
I have the same code that gets invoked for multiple forms of input. For example, a listener that listens to mouse events, key events, and focus events, but all methods do the same thing: repaint the source. This would mean that my code would look like this:
Notice how ugly this is? There are 10 different methods for this, when ultimately the only thing we care about is getting the source off the event (which is specified by
EventObject, by the way, which is why they used that in their example) and callingrepainton it.With Guava’s
EventBus, this gets super, super simple. All I need in myGuavaIsAwesomeComponentRepainterclass is one method:When you register this with an
EventBusand later fire, say, aMouseEventon it:And later:
This will call the
doSomethingmethod onComponentRepainterbecause it will not only fire the event to@Subscribemethods withMouseEventfor the parameter, but also to any methods that have a parameter that is assignable fromMouseEvent. In other words, becauseMouseEventextendsEventObject, Guava’sEventBuswill pass it to anything that acceptsEventObject. If we madedoSomethingacceptObject, then we can get every event that’s posted to theEventBus, making it a sort of global listener (because everything in Java extendsObject).The same thing applies to interfaces as well. If you pass a concrete implementation to
EventBusof some interface, then@Subscribemethods that use the interface (as opposed to the concrete type) will be called. It’s much more flexible, and overcomes the “10 useless methods” approach.