11

I'm getting the following error in one of my classes on the when attempting to unregister it.

java.lang.IllegalArgumentException: missing event handler for an annotated method. Is [DerivedClass] registered?" at com.google.common.eventbus.EventBus.unregister(EventBus.java:227)

The class calling unregister(this) has the public @Subscribe annotated method.

Jeff Axelrod
  • 27,676
  • 31
  • 147
  • 246

2 Answers2

18

The problem was that the error message misled me to think there was something wrong with the annotations. It was in fact that the class was unregistering itself twice due to some unexpected flow of control.

Jeff Axelrod
  • 27,676
  • 31
  • 147
  • 246
  • @PiotrekDe, It would be cool if you could post your comment as an answer to help others – fernandohur Jul 11 '13 at 22:18
  • 1
    Its also possible that you havn't registered your handler at all. Even if this should be obvois, in a multithreaded envirenment it may be possible that the unregister method is called before the register method. – Chris Aug 02 '13 at 21:23
  • I wonder why throw at all? What's the harm in attempting to unregister instance if not already registered? – Klaus Nji May 22 '19 at 20:27
4

A source code explanation:

/**
   * Unregisters all handler methods on a registered {@code object}.
   *
   * @param object  object whose handler methods should be unregistered.
   * @throws IllegalArgumentException if the object was not previously registered.
   */
  public void unregister(Object object) {
    Multimap<Class<?>, EventHandler> methodsInListener = finder.findAllHandlers(object);
    for (Entry<Class<?>, Collection<EventHandler>> entry : methodsInListener.asMap().entrySet()) {
      Class<?> eventType = entry.getKey();
      Collection<EventHandler> eventMethodsInListener = entry.getValue();

      handlersByTypeLock.writeLock().lock();
      try {
        Set<EventHandler> currentHandlers = handlersByType.get(eventType);
        if (!currentHandlers.containsAll(eventMethodsInListener)) {
          throw new IllegalArgumentException(
              "missing event handler for an annotated method. Is " + object + " registered?");
        }
        currentHandlers.removeAll(eventMethodsInListener);
      } finally {
        handlersByTypeLock.writeLock().unlock();
      }
    }
  }
Blundell
  • 75,855
  • 30
  • 208
  • 233