Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2007 The Guava Authors
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package com.google.common.eventbus;
 
 
 import java.util.Set;

A HandlerFindingStrategy for collecting all event handler methods that are marked with the Subscribe annotation.

Author(s):
Cliff Biffle
Louis Wasserman
 
A thread-safe cache that contains the mapping from each class to all methods in that class and all super-classes, that are annotated with @Subscribe. The cache is shared across all instances of this class; this greatly improves performance if multiple EventBus instances are created and objects of the same class are registered on all of them.
 
   private static final LoadingCache<Class<?>, ImmutableList<Method>> handlerMethodsCache =
       CacheBuilder.newBuilder()
           .weakKeys()
           .build(new CacheLoader<Class<?>, ImmutableList<Method>>() {
             @Override
             public ImmutableList<Methodload(Class<?> concreteClassthrows Exception {
               return getAnnotatedMethodsInternal(concreteClass);
             }
           });

  
This implementation finds all methods marked with a Subscribe annotation.
 
   @Override
   public Multimap<Class<?>, EventHandlerfindAllHandlers(Object listener) {
     Multimap<Class<?>, EventHandlermethodsInListener = HashMultimap.create();
     Class<?> clazz = listener.getClass();
     for (Method method : getAnnotatedMethods(clazz)) {
       Class<?>[] parameterTypes = method.getParameterTypes();
       Class<?> eventType = parameterTypes[0];
       EventHandler handler = makeHandler(listenermethod);
       methodsInListener.put(eventTypehandler);
     }
     return methodsInListener;
   }
 
   private static ImmutableList<MethodgetAnnotatedMethods(Class<?> clazz) {
     try {
       return .getUnchecked(clazz);
     } catch (UncheckedExecutionException e) {
       throw Throwables.propagate(e.getCause());
     }
   }
 
   private static ImmutableList<MethodgetAnnotatedMethodsInternal(Class<?> clazz) {
     Set<? extends Class<?>> supers = TypeToken.of(clazz).getTypes().rawTypes();
     ImmutableList.Builder<Methodresult = ImmutableList.builder();
     for (Method method : clazz.getMethods()) {
       /*
        * Iterate over each distinct method of {@code clazz}, checking if it is annotated with
        * @Subscribe by any of the superclasses or superinterfaces that declare it.
        */
       for (Class<?> c : supers) {
         try {
           Method m = c.getMethod(method.getName(), method.getParameterTypes());
           if (m.isAnnotationPresent(Subscribe.class)) {
             Class<?>[] parameterTypes = method.getParameterTypes();
             if (parameterTypes.length != 1) {
               throw new IllegalArgumentException("Method " + method
                   + " has @Subscribe annotation, but requires " + parameterTypes.length
                   + " arguments.  Event handler methods must require a single argument.");
             }
            Class<?> eventType = parameterTypes[0];
            result.add(method);
            break;
          }
        } catch (NoSuchMethodException ignored) {
          // Move on.
        }
      }
    }
    return result.build();
  }

  
Creates an EventHandler for subsequently calling method on listener. Selects an EventHandler implementation based on the annotations on method.

Parameters:
listener object bearing the event handler method.
method the event handler method to wrap in an EventHandler.
Returns:
an EventHandler that will call method on listener when invoked.
  private static EventHandler makeHandler(Object listenerMethod method) {
    EventHandler wrapper;
    if (methodIsDeclaredThreadSafe(method)) {
      wrapper = new EventHandler(listenermethod);
    } else {
      wrapper = new SynchronizedEventHandler(listenermethod);
    }
    return wrapper;
  }

  
Checks whether method is thread-safe, as indicated by the AllowConcurrentEvents annotation.

Parameters:
method handler method to check.
Returns:
true if handler is marked as thread-safe, false otherwise.
  private static boolean methodIsDeclaredThreadSafe(Method method) {
    return method.getAnnotation(AllowConcurrentEvents.class) != null;
  }
New to GrepCode? Check out our FAQ X