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

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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章