事件分析,采用代理和反射

来源:互联网 发布:怎么打罗马数字mac 编辑:程序博客网 时间:2024/04/28 23:28

package debug;

import java.awt.*;
import java.beans.*;
import java.lang.reflect.*;

public class EventTracer {
 public EventTracer() {
  handler = new InvocationHandler() {
   @Override
   public Object invoke(Object proxy, Method method, Object[] args) {
    System.out.println(method + ":" + args[0]);
    return null;
   }
  };
 }
 
 public void add(Component c) {
  try {
   //分析寻找这个组件中的形如:addXxxListener(XxxEvent)的所有方法
   BeanInfo info = Introspector.getBeanInfo(c.getClass());
   //对于每一个匹配的方法,都会生成一个EventSetDescriptor对象
   EventSetDescriptor[] eventSets = info.getEventSetDescriptors();
   for(EventSetDescriptor eventSet : eventSets) {
    //将这个对象传递给addListener方法
    addListener(c, eventSet);
   }
  } catch (Exception e) {
  }
  
  //如果该组件是一个容器
  if(c instanceof Container) {
   //递归列出其中的每一个组件
   for(Component comp : ((Container)c).getComponents()) {
    //递归调用add方法
    add(comp);
   }
  }
 }
 
 /**
  * @param c 监测其事件的组件
  * @param eventSet 事件设置的描述符
  */
 public void addListener(Component c, EventSetDescriptor eventSet) {
  Object proxy = Proxy.newProxyInstance(null, new Class[] {eventSet.getListenerType()}, handler);
  Method addListenerMethod = eventSet.getAddListenerMethod();
  try {
   addListenerMethod.invoke(c, proxy);
  } catch (Exception e) {
  }
 }
 
 private InvocationHandler handler;
}