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

耗尽温柔 提交于 2019-12-21 17:47:18

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/21007276/how-to-implement-language-level-events-similar-to-c-sharp-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!