public class EventHandler
{
private List<Event> objects ;
public EventHandler()// 构造方法,定义event类型的ArrayList
{
objects = new ArrayList<Event>();
}
// 添加事件
public void addEvent (Object object, String methodName)
{
objects .add (new Event(object, methodName));
}
// 通知执行方法
public void notifyExcute (Object[] Prams) throws Exception
{
for (Event e : objects )
{
e.invoke (Prams);
}
}
}
自定义Event,反射机制
import java.lang.reflect.Method;
public class Event
{
// 要执行的对象
private Object object ;
// 要执行的方法名称
private String methodName ;
// 要执行方法的参数的类型
private Class[] paramTypes ;
public Event()
{
}
public Event(Object object, String methodName)
{
this .object = object;
this .methodName = methodName;
}
// 根据参数数组生成参数的类型数组
private void createParamTypes (Object[] params)
{
this .paramTypes = new Class[params.length ];
for (int i = 0 ; i < params.length ; i++)
{
this .paramTypes [i] = params[i].getClass ();//获取对象的类型
}
}
public Object getObject ()
{
return object ;
}
private Class[] getParamTypes ()
{
// TODO Auto-generated method stub
return paramTypes ;
}
private String getMethodName ()
{
return methodName ;
}
// 若干setter getter省略
public void setParamTypes (Class[] paramTypes)
{
this .paramTypes = paramTypes;
}
// 执行该对象的该方法
public void invoke (Object[] Prams) throws Exception
{
createParamTypes (Prams);
Method method = object .getClass ().getMethod (this .getMethodName (), this .getParamTypes ());
if (null == method)
{
return ;
}
method.invoke (this .getObject (), Prams);
}
}
运用: EventHandler a = new EventHandler(); a.addEvnt(this,"meathodA"); a.notifyExcute(new Object[]{});//如果a中有多个方法,那么会执行所有方法