用Java注解+反射模拟Guava中EventBus

之前使用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学习之路还很漫长,幸运的是我在刚毕业就遇到了两个好老师——宏哲和超哥,不幸的是两个人不到半年都离职了,而我也离开了原来的公司,本来想到北京寻找更大的平台,结果现在这家公司却各方面不尽如人意,现在唯一能靠的只有自己了,带着两位前辈教给我的求知精神独自在技术的道路上走下去吧……

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值