Does Java have native support for events, similar to that of C#?

前端 未结 9 1985
眼角桃花
眼角桃花 2020-12-19 03:19

I\'m a bit confused from what I\'ve heard Java doesn\'t do events.

But I know that it does GUI events.

Am I missing something? Does java have an event handli

相关标签:
9条回答
  • 2020-12-19 03:44

    There is no native support in Java - you will have to implement the Observer Pattern (aka Subcribe/Publish). Its pretty straight forward - not more than a a dozen lines of code.

    0 讨论(0)
  • 2020-12-19 03:50

    As you already stated, you can do the exact same thing with the publisher-subscriber/Observer pattern. It just requires a bit more legwork.

    And no, Java does not have native support for events, like C# does with delegates.

    0 讨论(0)
  • 2020-12-19 03:50

    Here is an article on the topic also see Which Actor model library/framework for Java?

    0 讨论(0)
  • 2020-12-19 03:50

    You need threads. The GUI in java has events, because there is a dedicated thread for UI events to dispatch. There is also something calle "Observer" and "Observable" (this is the taste neutral version of the event listeners from the GUI stuff) but is just the design pattern...

    0 讨论(0)
  • 2020-12-19 03:52

    The Subscribe/Publish mechanism proposed by others here will let you implement synchronous events. For asynchronous event loops (fire and forget) You may want to look at "actors". An Actor<A> consists of a handler for messages (events) of type A, as well as a threading strategy for executing the handler. This lets you do concurrent, asynchronous event handling like the following:

    public class EventExample {
      public static void main(String[] args) {
        while ((char c = System.in.read()) >= 0) {
          eventHandler.act(c);
        }
      }
    
      public static Actor<Character> eventHandler =
        Actor.actor(Strategy.simpleThreadStrategy(), new Effect<Character>() {
          public void e(Character c) {
            // Do something with c here.
          }
        });
    }
    

    Get the actors library here. See the Javadoc here.

    0 讨论(0)
  • 2020-12-19 03:56

    I'm not knowledgeable about C#, but Java Beans that are not UI components can certainly notify Listeners about state changes using Events:

    http://java.sun.com/developer/onlineTraining/Beans/beans02/

    This has been part of the Java Beans spec since it first came out. Note the date on the tutorial: it's vintage 2000.

    The source and listener have to be running in the same JVM. You'd have to use a proxy to communicate with something running in another JVM, but it could be done.

    I Googled for the C# events tutorial and found this. Java's registering of listeners and firing of property changed events was reminiscent of what I saw when I skimmed the C# tutorial. Did I miss something important? (I'll admit that I didn't read deeply - no time right now.)

    0 讨论(0)
提交回复
热议问题