Java 番石榴';s EventBus-@Subscribe的可见性
接口方法的注释不会继承到实现该接口的对象afaik 我想与Guava的EventBus一起使用一个接口,它要求对象具有一个用Java 番石榴';s EventBus-@Subscribe的可见性,java,guava,event-bus,greenrobot-eventbus,Java,Guava,Event Bus,Greenrobot Eventbus,接口方法的注释不会继承到实现该接口的对象afaik 我想与Guava的EventBus一起使用一个接口,它要求对象具有一个用@Subscribe注释的回调方法。 我想知道是否可以简单地将该注释放入接口中,并让对象实现该侦听器接口。根据,这应该不起作用。但是,它确实可以工作(请参见下面的代码) 为什么? 我的机器是带有Windows7的Java1.8.0_151(32位) import static org.junit.Assert.assertEquals; import org.junit.T
@Subscribe
注释的回调方法。
我想知道是否可以简单地将该注释放入接口中,并让对象实现该侦听器接口。根据,这应该不起作用。但是,它确实可以工作(请参见下面的代码)
为什么?
我的机器是带有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 ++;
}
}
}
你是对的。。。而且是错误的。
您是对的,注释不是继承的。您可以通过这样一个测试来检查它MyListener.class.getMethod(“onEvent”,MyEvent.class).getAnnotation(Subscribe.class)!=空
但是,如果订阅方法是在接口中定义的,那么注册该方法是正确的
因此,在过去,如果声明方法中的任何一个被注释,那么它们注册的实现都会被订阅,这一点最不奇怪
我必须承认,我检查了你的问题,没有看到任何关于你问题的具体内容,尽管我觉得有必要提及。我记得几年前的讨论,不得不在封闭的问题中找到答案。哇,我真的希望这是有文档记录的,所以我知道这样使用它是“正确的”(虽然整个总线设计为无接口工作,但我在某处读到了该讨论)。当这种行为发生变化时,将其记录下来也可能意味着一个变更通知,对吗?谢谢!