java Guava的@Subscribe事件总线可见性
接口方法的注释不会继承到实现该接口的对象afaikSO search results
我想与Guava的EventBus一起使用一个接口,它要求对象有一个用@Subscribe
注释的回调方法。
我想知道是否可以简单地将该注释放入接口中,并让对象实现该侦听器接口。根据above,这应该不起作用。但是,它确实可以工作(参见下面的代码)
为什么?
我的机器是带有Windows7的Java1.8.0_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 楼答案
你是对的。。。而且是错误的
您是对的,^{} 注释不是继承的。你可以通过这样的测试来检查它
但是,如果订阅方法是在接口中定义的,那么注册订阅方法是正确的
因此this was discussed at length within the Guava team在过去和最不令人惊讶的原则中,如果声明方法中的任何一个被注释,那么它们注册的实现就被订阅了
我必须承认,我检查了{a3}和{a4},没有看到关于你的问题的任何具体内容,尽管我觉得有必要提及。我记得几年前的讨论,必须在封闭的问题中找到答案