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
  * 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.
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import  javax.annotation.Nullable;

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

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 =
           .build(new CacheLoader<Class<?>, ImmutableList<Method>>() {
             public ImmutableList<Methodload(Class<?> concreteClassthrows Exception {
               return getAnnotatedMethodsInternal(concreteClass);

This implementation finds all methods marked with a Subscribe annotation.
   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);
     return methodsInListener;
   private static ImmutableList<MethodgetAnnotatedMethods(Class<?> clazz) {
     try {
       return .getUnchecked(clazz);
     } catch (UncheckedExecutionException e) {
       throw Throwables.propagate(e.getCause());
   private static final class MethodIdentifier {
     private final String name;
     private final List<Class<?>> parameterTypes;
     MethodIdentifier(Method method) {
       this. = method.getName();
       this. = Arrays.asList(method.getParameterTypes());
     public int hashCode() {
      return Objects.hashCode();
    public boolean equals(@Nullable Object o) {
      if (o instanceof MethodIdentifier) {
        MethodIdentifier ident = (MethodIdentifiero;
        return .equals( && .equals(ident.parameterTypes);
      return false;
  private static ImmutableList<MethodgetAnnotatedMethodsInternal(Class<?> clazz) {
    Set<? extends Class<?>> supers = TypeToken.of(clazz).getTypes().rawTypes();
    Map<MethodIdentifierMethodidentifiers = Maps.newHashMap();
    for (Class<?> superClazz : supers) {
      for (Method superClazzMethod : superClazz.getMethods()) {
        if (superClazzMethod.isAnnotationPresent(Subscribe.class)) {
          Class<?>[] parameterTypes = superClazzMethod.getParameterTypes();
          if (parameterTypes.length != 1) {
            throw new IllegalArgumentException("Method " + superClazzMethod
                + " has @Subscribe annotation, but requires " + parameterTypes.length
                + " arguments.  Event handler methods must require a single argument.");
          MethodIdentifier ident = new MethodIdentifier(superClazzMethod);
          if (!identifiers.containsKey(ident)) {
    return ImmutableList.copyOf(identifiers.values());

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

listener object bearing the event handler method.
method the event handler method to wrap in an EventHandler.
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.

method handler method to check.
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