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

C # has an event concept at the language level , using the reserved event and delegate keywords to identify publisher and subscriber methods. It was asked if Java has built-in support for this , but the answer is clearly missing. There are several alternatives that include using AWT / Swing-style events, creating your own observer template, or other ways to publish / sign. It is possible, but, as one answer said, "it just takes a little more work."

In general, any implementation follows the same typed approach and can be automated. Java has different mechanisms for metaprogramming, for example. AOP or AST. How to implement C # events in Java to ensure minimal footwork?

Perhaps the Lombok Project ?

+5
java c # events porting
source share
1 answer

If you have a distributed environment, use Akka .

Otherwise, you have several options.

Guava has an EvenBus . Guava would be my choice because it has become one of the main libraries that use Java projects like apache commons, slf4j, etc.

A Google search for the "java event library" shows a few more options.

Otherwise, write a class that contains subscribers and will send them events as they arrive. Easy but careful with concurrency.

+1
source share

All Articles