// EventBusBuidler.java
/** Adds an index generated by EventBus’ annotation preprocessor. */
public EventBusBuilder addIndex(SubscriberInfoIndex index) {
if (subscriberInfoIndexes == null) {
subscriberInfoIndexes = new ArrayList<>();
}
subscriberInfoIndexes.add(index);
return this;
}
通过 addIndex()
将 SubscriberInfoIndex
往这个列表里面加。再往上找,没有了,addIndex()没有出现在任意一处被调用的地方。
也就是说,这个方法,是外部调用的。
它的英文注释我翻译一下:通过EventBus的注解处理器添加一个索引 。
这就说明了这个方法,是由注解器产生的Java文件调用。这也说明了,如果我们不使用注解处理器,EventBus寻找 @Subcriber
的做法,永远是 反射 + 遍历。
2. 通过EventBusAnnotationProcessor生成Java文件
==========================================================================================================
EventBusAnnotationProcessor
需要引入,示例代码如下:
// build.gradle
android {
defaultConfig {
javaCompileOptions {
annotationProcessorOptions {
arguments = [ eventBusIndex : ‘com.example.myapp.MyEventBusIndex’ ]
}
}
}
}
dependencies {
def eventbus_version = ‘3.2.0’
implementation “org.greenrobot:eventbus:$eventbus_version”
annotationProcessor “org.greenrobot:eventbus-annotation-processor:$eventbus_version”
}
然后在项目中,写入 @Subscribe
方法:
public class MainActivity extends AppCompatActivity {
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMainActivityEvent(MainActivityEvent event){
}
…
}
点击编译,就会在下图目录中看到编译时生成的文件:
来看下文件内容:
public class MyEventBusIndex implements SubscriberInfoIndex {
private static final Map<Class<?>, SubscriberInfo