A brief introduction to java for event driven mechanism

  • 2020-10-07 18:42:23
  • OfStack

Due to project requirements, Java needs to be provided with a set of class libraries that support event-driven mechanisms similar to event and delegate mechanisms in C#. As is known to all, Java language itself and its standard library does not provide event-driven mechanism related interfaces, although Swing (and I don't think it belongs to the standard library, because 1, nobody use:) existing in the relevant class supports the mechanism so as to realize the event processing components, but it is, after all, coupled with GUI photograph, and in other types of applications to use seem strange, lack of universality. Therefore, it is necessary to implement a common Java event-driven mechanism library and then apply it to common Java applications, although it is not difficult :)

Let's first examine the event-driven writing method of C#. The event keyword provided in C# can easily be used to define an event, and then by adding an event handler to the event (as in C# 1, the delegate (delegate) refers to a function), the triggered event can invoke the associated handler, which is an event-driven process. Such as:


// Define the event and the corresponding delegate 
public event MyDelegate Click;
public delegate void MyDelegate();

// Define the entrusted 
void OnClick(){
  console.writeline("you just clicked me!");
}

// Associate the delegate with the event 
Click += OnClick;

// Triggering event 
Click();

The above code is a simple example of an event-driven mechanism implemented with C#, which is apparently very simple because of the language level (CLR) convenience provided by C#. Unfortunately, Java does not provide this convenience. It has to be done artificially. The following article provides two ways to implement event-driven mechanisms for reference only.

Observer model

Observer mode is a common design mode. The observer (Observer) first subscrives to the observed object (Subject). In this way, once certain changes occur to the observed object (Subject), the observer will be informed of the changes (Observer).

This design pattern is just right for event-driven mechanisms, where an event (event) is equivalent to an observed object (Subject), and once the event is triggered, the event handler (the delegate in C#) can be seen as an observer. So you can implement the above functionality as follows.


/* Event classes */
public Event {
  // Event handlers associated with events 
  public ArrayList<Callback> callbackList;
  
  // Event trigger function 
  public void emit(){
    for(Callback cb : callbackList){
      cb.run();
    }
  }
  
  // Register event handlers 
  public registerCallback(Callback cb){
    callbackList.add(cb);
  }
}

/* Event handler class */
public interface Callback {
  void run();
}

public OnClick implements Callback {
  // function 
  public void run(){
    System.out.println("you just clicked me!");
  }
  
  
/* Implement event-driven */
Event e = new Event(); 
// will OnClick Event handlers are registered to the event 
e.registerCallback(new OnClick()); 
// Triggering event 
e.emit();

The Java code above implements a simple event-driven mechanism. The principle is simple, and it is a typical application case of the observer pattern.

Using the reflection

The Java language provides powerful reflection capabilities that allow you to take and manipulate individual components of a class (such as class names, class member functions, class properties, and so on) at runtime. The following USES reflection to implement a simple event-driven mechanism.


/* Event handler class */
public class EventHandler {
  // The event source 
  private Object sender;
  // Event handler name (for reflection) 
  private String callback;
  
  public EventHandler(Object sender, String callback){
    this.sender = sender;
    this.callback = callback;
  }
  
  // Events trigger 
  public void emit(){
  Class senderType = this.sender.getClass();
  try {
    // Gets and invokes the event source sender The event handler function of 
    Method method = senderType.getMethod(this.callback);
    method.invoke(this.sender);
    } catch (Exception e2) {
      e2.printStackTrace();
    }
  }
}


/* The event source */
public class Button(){
  /* You can set it here Button Related attributes of a class, such as name, etc */
  private String name;
  ...
  
  
  // Event handler 
  public void onClick(){
    System.out.println("you just clicked me!");
  }
}
  
  
/* Implement an event-driven mechanism */
Button b = new Button();
if(/* Receive button click signal */){
  EventHandler e = new EventHandler(b, "onClick");
  e.emit();
}

The above code shows the implementation of reflection event driven mechanism, using the reflection mechanism has the advantage of its powerful extensibility, such as my event handler can introduce a EventArgs parameter, which can make the event itself with parameters, carry more information so that event, rewrite the following code of the event handler is as follows:


public class EventArgs {
  // parameter 
  String p1;
  Integer p2;
  ...
  
}

//onClick Event handler rewriting 
public void onClick(Object sender, EventArgs e){
  // parameter e Provide more information 
  System.out.println("Hello, you clicked me! " + e.p1 + e.p2);
}

// Trigger function emit rewrite 
public void emit(EventArgs e){
Class senderType = this.sender.getClass();
try {
  // Gets and invokes the event source sender The event handler function of 
  Method method = senderType.getMethod(this.callback, this.getClass(), e.getClass());
  method.invoke(this.sender, this.sender, e);
  } catch (Exception e2) {
    e2.printStackTrace();
  }
}

Is it deja vu? Yes, Visual studio has almost exactly the same form as the event handler (onClick function in the code) that you automatically generated when writing Winform forms with C#, but in this case we implemented it with Java.

Of course, in addition to the two methods mentioned above to implement the event-driven mechanism of Java, there are a number of other methods, such as using the inner classes of Java, and I have written some example code, which I will leave for later.


Related articles: