search
HomeJavajavaTutorialDetailed explanation of guava eventbus example code

Detailed explanation of guava eventbus example code

Jun 21, 2017 am 09:25 AM
eventbusguavacodeanalyze

Before analyzing guava eventbus, let’s take a look at how the traditional observer pattern is written:

The Subject interface is an abstract topic, equivalent to the observed, it holds a listener The list of observers, the attach method registers the listener in this list, the detach method cancels the listener, and the notify method is used to notify the listeners in the list when an event occurs

is usually called in the notify implementation method The listener's update method.

Observer is an abstract observer with an update method. The update method is called by the notify method of the specific theme.

This is a traditional programming method for interfaces. The difference is that eventbus uses ""implicit interface", a programming method based on java Annotation.

The difference is: the corresponding relationship of this "implicit interface" is generated when the program is running , and based on the true meaning of the corresponding relationship between the interface and the implementation is established at compile time, in contrast, the "implicit interface" is more flexible

Let's analyze how the implicit interface and implementation establish binding For a definite relationship, look at the code:

 1 ##SubscriberRegistry类的register方法 2 void register(Object listener) { 3     Multimap<class>, Subscriber> listenerMethods = findAllSubscribers(listener); 4  5     for (Map.Entry<class>, Collection<subscriber>> entry : listenerMethods.asMap().entrySet()) { 6       Class> eventType = entry.getKey(); 7       Collection<subscriber> eventMethodsInListener = entry.getValue(); 8  9       CopyOnWriteArraySet<subscriber> eventSubscribers = subscribers.get(eventType);10 11       if (eventSubscribers == null) {12         CopyOnWriteArraySet<subscriber> newSet = new CopyOnWriteArraySet<subscriber>();13         eventSubscribers = MoreObjects.firstNonNull(14             subscribers.putIfAbsent(eventType, newSet), newSet);15       }16 17       eventSubscribers.addAll(eventMethodsInListener);18     }19   }</subscriber></subscriber></subscriber></subscriber></subscriber></class></class>

The useful part of this method is line 3. A rough analysis of the rest of the code is to facilitate this Mutimap, which combines listeners of the same type of events. Subsriber is added to the corresponding set. If the set of Subsriber for the current type of event is empty, then add an empty set first.

Follow the method in line 3 above:

 1 /** 2    * Returns all subscribers for the given listener grouped by the type of event they subscribe to. 3    */ 4   private Multimap<class>, Subscriber> findAllSubscribers(Object listener) { 5     Multimap<class>, Subscriber> methodsInListener = HashMultimap.create(); 6     Class> clazz = listener.getClass(); 7     for (Method method : getAnnotatedMethods(clazz)) { 8       Class>[] parameterTypes = method.getParameterTypes(); 9       Class> eventType = parameterTypes[0];10       methodsInListener.put(eventType, Subscriber.create(bus, listener, method));11     }12     return methodsInListener;13   }</class></class>

The core method in this method is line 7, which obtains all methods with Subscribe annotation of a specific class. The rest of the code means to get these methods, put them into a multi-value map, and then return ##.

#Follow up the method in line 7 above:

1 private static ImmutableList<method> getAnnotatedMethods(Class> clazz) {2     return subscriberMethodsCache.getUnchecked(clazz);3   }</method>
After following this, eclipse has no choice but to follow. It is suspected that the internal anonymous class has called a certain method ( Eclipse also displays incomplete call links for internal anonymous classes)

Let’s take a look at this

subscriberMethodsCache
1 private static final LoadingCache<class>, ImmutableList<method>> subscriberMethodsCache =2       CacheBuilder.newBuilder()3           .weakKeys()4           .build(new CacheLoader<class>, ImmutableList<method>>() {5             @Override6             public ImmutableList<method> load(Class> concreteClass) throws Exception {7               return getAnnotatedMethodsNotCached(concreteClass);8             }9           });</method></method></class></method></class>
When the load method is called, the getAnnotatedMethodsNOtCached of the current class is called. Method, follow this method:

 1 private static ImmutableList<method> getAnnotatedMethodsNotCached(Class> clazz) { 2     Set extends Class>> supertypes = TypeToken.of(clazz).getTypes().rawTypes(); 3     Map<methodidentifier> identifiers = Maps.newHashMap(); 4     for (Class> supertype : supertypes) { 5       for (Method method : supertype.getDeclaredMethods()) { 6         if (method.isAnnotationPresent(Subscribe.class) && !method.isSynthetic()) { 7           // TODO(cgdecker): Should check for a generic parameter type and error out 8           Class>[] parameterTypes = method.getParameterTypes(); 9           checkArgument(parameterTypes.length == 1,10               "Method %s has @Subscribe annotation but has %s parameters."11                   + "Subscriber methods must have exactly 1 parameter.",12               method, parameterTypes.length);13 14           MethodIdentifier ident = new MethodIdentifier(method);15           if (!identifiers.containsKey(ident)) {16             identifiers.put(ident, method);17           }18         }19       }20     }21     return ImmutableList.copyOf(identifiers.values());22   }</methodidentifier></method>
The second line means to get the current class itself + all the classes of the current class’s parent class and interface, and put them in a Set

Line 4 traverses this Set

Line 5 traverses all methods of each class

Line 6 calls Method’s isAnnotationPresent method to determine that the target method has the @Subscribe annotation, and This method cannot be a "composite method"

Put the compound condition method into the map on line 16 and return it on line 21!

The above is the detailed content of Detailed explanation of guava eventbus example code. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment