使用开源的org.greenrobot.EventBus可以更好地维护事件处理,取代反射(参考:https://blog.csdn.net/haoranhaoshi/article/details/103816810),取代自写监听(参考:https://blog.csdn.net/haoranhaoshi/article/details/84250934)。
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
public class EventBusTest {
public EventBusTest(){
// 本类或子类必须有@Subscribe的pulic且非static的方法
EventBus.getDefault().register(this);
}
public static void main(String[] args) {
new EventBusTest();
Event event = new Event();
event.setType(EventType.TEST);
event.setData("Event Bus Test ", 1);
// post方法可以和注册、取消注册、执行事件这三个方法一个类,也可以不是一个类
// EventBus.getDefault().unregister(this);注册、取消注册是一个对象
EventBus.getDefault().post(event);
}
/**
* EventBus的响应方法加注解@Subscribe(threadMode = ThreadMode.MAIN),响应方法名无特殊要求
* 此方法必须public
* 此方法必须非 static
*
* @param event
*/
@Subscribe(threadMode = ThreadMode.MAIN)
public void eventBusAction(Event event) {
if(EventType.TEST.equals(event.getType())){
Object[] data = (Object[])event.getData();
System.out.println(data[0]);
System.out.println(data[1]);
}
}
}
public class Event {
private String type;
private Object data;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Object getData() {
return data;
}
public void setData(Object... data) {
this.data = data;
}
}
public class EventType {
public static final String TEST = "test";
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.hao.test</groupId>
<artifactId>event-bus</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.greenrobot</groupId>
<artifactId>eventbus</artifactId>
<version>3.1.1</version>
</dependency>
</dependencies>
</project>
注意:EventBus.getDefault().post(event);所在类A必须能找到EventBus.getDefault().register(this);所在类B。比如在模块化工程中,类B所在模块2必须导出类B所在的包,即模块2的module-info.java必须exports 类B所在的包(此包不能是类B所在包的上级包)。