代码之家  ›  专栏  ›  技术社区  ›  Moritz

Guava的EventBus-订阅的可见性

  •  1
  • Moritz  · 技术社区  · 8 年前

    接口方法的注释不会继承到实现该接口的对象afaik。 SO search results

    我想与Guava的EventBus一起使用一个接口,它要求对象有一个带注释的回调方法 @Subscribe 。 我想知道是否可以简单地将该注释放入接口中,并让对象实现该侦听器接口。根据 above ,这应该 工作然而 确实有效 (参见下面的代码)。

    为什么?

    我的机器是带有Windows 7的Java 1.8.0\u 151(32位)。

    import static org.junit.Assert.assertEquals;
    import org.junit.Test;
    import com.google.common.eventbus.EventBus;
    import com.google.common.eventbus.Subscribe;
    
    /**
     * This test should fail, but... it works!
     */
    public class EventTests {
    
    
        @Test
        public void test_events_are_heard() {
    
            MyListener listener = new MyListener();
            DeafListener deafListener = new DeafListener();
            EventBus bus = new EventBus();
            bus.register(listener);
            bus.register(deafListener);
            bus.post(new MyEvent());
            assertEquals(1, listener.eventCount);     // ok
            assertEquals(0, deafListener.eventCount);   // ok
        }
    
        // this interface includes the @Subscribe annotation
        private interface Listener {
            @Subscribe
            public void onEvent(MyEvent event);
        }
    
        // this interface does not include the @Subscribe annotation
        private interface NoListener {
            public void onEvent(MyEvent event);
        }
    
        // just something different from Object
        private static class MyEvent {
        }       
    
        // implementation of "Listener" (with @Subscribe in interface)
        private static class MyListener implements Listener {
            int eventCount = 0;
            @Override
            public void onEvent(MyEvent event) {
                eventCount ++;
            }
        }
    
        // IDENTICAL implementation as above, but of "NoListener" 
        // (without @Subscribe in interface)
        private static class DeafListener implements NoListener {
            int eventCount = 0;
            @Override
            public void onEvent(MyEvent event) {
                eventCount ++;
            }
        }
    
    }
    
    1 回复  |  直到 8 年前
        1
  •  3
  •   Olivier Grégoire    8 年前

    你是对的。。。而且是错误的。

    你说得对 @Subscribe 批注未继承。你可以通过这样的测试来检查 MyListener.class.getMethod("onEvent", MyEvent.class).getAnnotation(Subscribe.class) != null

    然而 感觉 如果在接口中定义了订阅方法,则有权注册该方法。

    所以 this was discussed at length within the Guava team 在过去,最不令人惊讶的原则是,如果对任何声明方法进行了注释,那么就会订阅它们注册的实现。

    我必须承认我检查过了 the documentation the Javadoc 虽然觉得有必要提及你的问题,但没有看到任何关于你问题的具体内容。我记得多年前的讨论,必须在封闭的问题中找到答案。

    推荐文章