Read the source to practice the internal strength (i): Guava Eventbus

Source: Internet
Author: User
Tags object object oracle documentation eventbus

Now the eyes, open Source Library more and more, programmers often do not need to build their own wheels, you can find a desirable open source library for use. While we're working with all kinds of open source code, we don't need to know how that code is implemented. But understanding how they are implemented will not only enhance our own programming skills and programming skills, but also provide examples that we can emulate to learn a particular technical point.


Guava Introduction

Like boost to C++,guava, it's almost an integral part of Java programming. Guava covers a lot of interesting things, such as using functional programming in Java, new data structures such as BIMAP, and so on. In short, guava makes writing Java programs a better thing. There are a lot of interesting things in guava that can be guava on the official website. Guava

This article attempts to learn how to use annotation programming in Java by analyzing the source code of Guava's Eventbus. Eventbus Introduction

Publisher-subscriber This design pattern has long been explained in detail in Gof. is also one of the most common design patterns. While Eventbus is an implementation of Publisher and Subscriber, if you're using observer in JDK, take a look at TW's large blog, the observer of Java knowledge you should update, The use of Eventbus as a substitute for observer seems to be a must. How to use Eventbus

Messagescreen.java:

public class Messagescreen {
@Subscribe
public void Printmessage (String message) {
SYSTEM.OUT.PRINTLN (message);
}
}

Calling code:

Eventbus Eventbus = new Eventbus ();
Eventbus.register (New Messagescreen ());
Eventbus.post ("Hello screen");

Show Results:

Hello screen


Code Explanation:

When the register is called in the Eventbus, a Listeneris registered to the Eventbus. The listener here is messagescreen.

The method labeled @subscribe in Listener is EventHandler, which is invoked when Eventbus uses post to publish the Event . Corresponding to the previous example, EventHandler is Printmessage this method. The event is "Hello screen".

The parameter type in EventHandler is EventTypeand here is string. When Eventbus uses post, a different type of event is sent to the corresponding handler for processing.

So all the seemingly magical things happen in the @subscribe this mark. What the hell is annotation to do with it? How a way to mark the @subscribe can become a subscriber.


Annotation Programming

annotation is a metadata that provides information about a program, but this information is not part of the program that is annotation annotated. It does not affect the execution of the program being labeled.

Taking the above MessageListener as an example, DisplayMessage This method is labeled @subscribe, which is used in the register in Eventbus, not in the MessageListener.

annotation programming can be divided into roughly two parts, the first part is the annotation definition, the second part is to get the code that is annotation tag, and then do some specific actions for this part of the code. let's use Eventbus to explain how the two-part work is done. define annotation: @Subscribe

definition of Subscribe :

@Retention (Retentionpolicy.runtime)
@Target (Elementtype.method)
Public @interface Subscribe {
}


The @interface represents a annotation definition. @Retention and @target are predefined annotation.

@Retention indicate how subscribe this annotation is preserved. The @Retention (rententionpolicy.runtime) explains that subscribe this annotation can be used at run time.

@Target represents the subscribe where this annotation can be labeled. The @Target (Elementtype.method) explains subscribe is used to mark methods. The example that corresponds to the beginning Eventbus is Printmessage this method.


get the code tagged by annotation: how do you know the @subscribe method in Eventbus?

Code for Eventbus:

public void Register (object object) {
Multimap<class<?>, eventhandler> Methodsinlistener =
Finder. findallhandlers (object);
Handlersbytype.putall (Methodsinlistener);
}

When the register is Eventbus, the @subscribe method is identified by a finder in the Register's object. And according to EventType to classify, put in Handlersbytype. So when Eventbus post a new event, the corresponding EventHandler can be invoked according to the EventType.

code for Annotatedhandlerfinder :

     public multimap<class<?>, eventhandler> findallhandlers (Object listener) {
         multimap<class<?>, eventhandler> methodsinlistener = hashmultimap.create ();
         Class<?> clazz = Listener.getclass ();
         for (method: getannotatedmethods (clazz)) {
  &nbs P          class<?>[] parametertypes = Method.getparametertypes ();
             Class<?> eventtype = parametertypes[0];
             eventhandler handler = Makehandler (Listener, method);
             methodsinlistener.put (EventType, handler);
         }
         return Methodsinlistener;
    &NBSP;}

In findallhandlers this function, you will first call Getannotatedmethods to get all the methods labeled @subscribe in listener. The Listener and tagged methods are then placed in a data structure called EventHandler, and the first and only parameter type of method is recorded as EventType, which is used for distributing messages by type as a post. And then see how to get the @subscribe tag method:

private static immutablelist<method> Getannotatedmethods (class<?> clazz) {

For (Method Method:clazz.getMethods ()) {
if (method. Isannotationpresent(Subscribe.class)) {
.../Add to List
}
}
}

Getannotatedmethods first obtained all the methods of listener. Then iterate through the query whether there is a way to be @subscribe marked:method.isannotationpresent (Subscribe.class). if it is marked by @subscribe, it is added to the returned list. This, in fact, tells us that another benefit of this approach is that a class can no longer have only one update as a observer method. Instead, there can be multiple @subscribe labeled EventHandler, which are distinguished by the method name and EventType in the same class.


When the post in Eventbus is invoked, there is a series of queued and queued operations. The last call, the EventHandler Handleevent method.

Eventhandler.java

public void Handleevent (Object event) {
Method.invoke (Target,new object[]{event});
}

The method in Handleevent is a @subscribe that is marked in the register, and the first parameter target is the listener that is added to the register by invoking the Invoke method of methods. This invokes the method that is @subscribe.


Summary

1.Annotation programming is useful in many places, such as the @component of the @test,spring in the JUNIT4 that everyone is familiar with. So, to learn annotation, maybe we can write these easy to use programs.

2. In the complete implementation of Eventbus, there are many other technologies, such as multithreading, cache and guava other functions. For example Getannotatedmethods This method is not really to find annotated Methods, the real search is getannotatedmethodsinternal this method, during the use of cache. To focus on the use of annotation itself, there is no discussion.

3. When deciding whether or not to contain @subscribe, Annotatedhandlerfinder is actually checking the methods of all the parent classes. Because the annotation of the parent class itself is not inherited by the quilt class, if the subclass overrides the method of the parent class. Then the call to the isannotationpresent of the subclass returns false.

4. How to find out more about annotation details, you can access the official Oracle Documentation: Oracle Annotation


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.