C# has the notion of events on a language level, using the reserved keywords event
and delegate
to define publisher and subscriber methods. It has been asked if Java has native support for that but the answer is obviously no. There are several alternatives, which include using AWT/Swing styled events, building my own Observer pattern or using other means of publish/subscribe. It is possible but as one answer said, "just requires a bit more legwork."
In general any implementation follows the same typed approach and could be automated. Java has different mechanisms for meta programming, e.g. AOP or AST transformations. How would one implement the C# events in Java to allow for the least "legwork" possible?
Maybe Project Lombok?
If you have a distributed environment, use Akka.
Otherwise you have a few choices
Guava has EvenBus. Guava would be my choice because it has become one of the core libraries that Java projects use, like apache commons, slf4j etc.
Google search for "java event library" reveals a few more choices.
Otherwise, write a class that holds subscribers and dispatches to them the events as they come in. Easy, but careful with concurrency.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With