Guava Study notes: Eventbus

Source: Internet
Author: User
Tags eventbus

Guava Study notes: Eventbus

Reprint: http://blog.csdn.net/kiwi_coder/article/details/9338721

Now, under the eyes, there are more and more open source libraries, programmers often do not need to build their own wheels, you can find a desirable open source library for use. While we are using a wide variety of open source code, we do not need to know how the code is implemented. But understanding how they are implemented can not only improve our own programming and programming skills, but also provide examples of what we can imitate to learn a particular technical point.

Guava Introduction

As with 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 it a better thing to write Java programs. There are many interesting things in guava that can be found on the official website of Guava. Guava

This article attempts to learn how to use annotation programming in Java by analyzing the source code of the guava Eventbus.

Eventbus Introduction

Publisher-subscriber This design pattern is explained in detail in the GOF. is also one of the most commonly used design patterns. While Eventbus is an implementation of Publisher and Subscriber, if you're still using observer in the JDK, take a look at TW's big blog, "The observer of Java knowledge you should update," Using Eventbus instead of observer seems like a must.

Eventbus How to use

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 a register is called in Eventbus, a Listeneris registered to the Eventbus. The listener here is messagescreen.

The method that is labeled by @subscribe in listener is EventHandler, which is called when Eventbus uses post to publish an Event . In response to the previous example, EventHandler is the Printmessage method. The event is "Hello screen".

The parameter type in EventHandler is EventType, which is string. When Eventbus uses post, the type that will be more event is sent to the appropriate handler for processing.

As a result, all the seemingly magical things happen on the @subscribe mark. What the hell is that annotation for? How can a @subscribe method be turned into a subscriber?

Annotation programming

Annotation is a meta-data that provides information about a program, but this information is not part of the program that is labeled by annotation. It does not affect the execution of the annotated program.

Take the above MessageListener as an example, DisplayMessage This method is labeled @subscribe, this callout information is used in the register in the 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 tagged, and then do some specific operations for this part of the code. here's how to use Eventbus to explain how this two-part work is done.

Definition annotation: @Subscribe

definition of Subscribe :

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

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

@Retention indicates how subscribe this annotation was saved. The @Retention (Rententionpolicy.runtime) illustrates that subscribe this annotation can be used at run time.

@Target shows where this subscribe annotation can be labeled. The @Target (Elementtype.method) illustrates that subscribe is used for tagging methods. The example that corresponds to a beginning Eventbus is Printmessage this method.

Get the code that is tagged annotation: how do you know @subscribe method in Eventbus?

Eventbus's Code:

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

When the register is Eventbus, a finder is used to find the @subscribe method in the object of the register. and classify according to EventType, put in Handlersbytype. This way, when Eventbus post a new event, the corresponding EventHandler can be called according to the EventType.

Annotatedhandlerfinder's Code :

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

In the Findallhandlers function, the getannotatedmethods is called first to get all the methods that are marked @subscribe in listener. The listener and the method labeled @subscribe are then placed in a data structure called EventHandler, while the first and only parameter type of method is recorded as EventType used as a post when distributing messages by type. Then look at how to get the method that is labeled by @subscribe:

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 traverse the query whether there are methods that are @subscribe marked:method.isannotationpresent (Subscribe.class). If the @subscribe is marked, it is added to the returned list. This, in fact, tells us that another benefit of this approach is that there can be no more than one update as the Observer method in a class. Instead, there can be multiple @subscribe labeled EventHandler, which are distinguished by the method name and EventType when they are in the same class.

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

Eventhandler.java

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

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

Summarize

1.Annotation programming is useful in many places, such as the @component in the @test,spring of JUNIT4, which is familiar to everyone, and so on. So, learning annotation, maybe let us write these easy-to-use procedures.

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

3. When judging whether a @subscribe is included, Annotatedhandlerfinder actually examines 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. Isannotationpresent that call the subclass will return false.

4. To learn more about annotation, you can access the official documentation for Oracle: Oracle annotation

Guava Study notes: Eventbus

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.