之前使用EventBus,感觉通过Java的注解和反射能够模拟它的工作过程,今天做了尝试,主要实现订阅者订阅指定类型的消息,如果发送的消息是该类型则接收,否则就不接收。效果还不错,基本的功能都实现了。下面直接上代码。
首先要定义一个注解,用来标记订阅的方法:
package myeventbus;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.google.common.annotations.Beta;
@Beta
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MySubScribe {
}
然后是事件类MyEvent和订阅者MyEventSubscriber
package myeventbus;
public class MyEvent {
private int massage;
public MyEvent(int massage){
this.massage = massage;
}
public int getMassage(){
return massage;
}
}
package myeventbus;
public class MyEventSubscriber {
private int massage;
@MySubScribe
public void listen(MyEvent event){
this.massage = event.getMassage();
}
public int getMassage(){
return massage;
}
}
自己模拟的EventBus类
package myeventbus;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MyEventBus {
@SuppressWarnings("unused")
private Object massage;
private Class<?> cl;
private Object obj;
public void register(Object obj) {
cl = obj.getClass();
this.obj = obj;
}
public void post(Object massage) {
this.massage = massage;
for (Method m : cl.getDeclaredMethods()) {
MySubScribe sub = m.getAnnotation(MySubScribe.class);
if (sub != null) {
Class<?>[] params = m.getParameterTypes();
if (massage.getClass().equals(params[0])) {
try {
m.invoke(obj, massage);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
}
}
最后是测试类
package myeventbus;
public class MyEventBusTest {
public static void main(String[] args) {
MyEventSubscriber eventSubscriber = new MyEventSubscriber();
MyEventBus eventBus = new MyEventBus();
eventBus.register(eventSubscriber);
eventBus.post(new MyEvent(200));
System.out.println(eventSubscriber.getMassage());
}
}
这里仅仅是模拟,真正的源码我还没有看,主要是为了熟悉注解和反射的一些用法,Java学习之路还很漫长,幸运的是我在刚毕业就遇到了两个好老师——宏哲和超哥,不幸的是两个人不到半年都离职了,而我也离开了原来的公司,本来想到北京寻找更大的平台,结果现在这家公司却各方面不尽如人意,现在唯一能靠的只有自己了,带着两位前辈教给我的求知精神独自在技术的道路上走下去吧……