简体   繁体   中英

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, eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM