Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement language level events similar to C# in Java

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?

like image 593
Peter Kofler Avatar asked Nov 11 '22 15:11

Peter Kofler


1 Answers

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.

like image 198
Daniel Nuriyev Avatar answered Nov 14 '22 21:11

Daniel Nuriyev