如何在Java中实现与C#类似的语言级别事件 [英] How to implement language level events similar to C# in Java

查看:298
本文介绍了如何在Java中实现与C#类似的语言级别事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#具有语言级别的事件的概念,使用保留的关键字事件委托定义发布者和订阅者方法。已经询问Java是否具有本机支持这个,但答案显然不是。有几个替代方案,其中包括使用AWT / Swing风格的事件,建立我自己的观察者模式或使用其他发布/订阅方式。这是可能的,但正如一个答案所说,只需要更多的脚步。



一般来说,任何实现都遵循相同的类型方法,可以自动化。 Java具有不同的元编程机制,例如AOP或AST转化。如何在Java中实现C#事件,以使最少的legwork成为可能?



也许项目龙目岛

解决方案

如果您有分布式环境,请使用 Akka



否则你有几个选择



Guava有 EvenBus 。番石榴是我的选择,因为它已经成为Java项目使用的核心库之一,如apache commons,slf4j等。



Google搜索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?

解决方案

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.

这篇关于如何在Java中实现与C#类似的语言级别事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆