Java中大家對addListener之類的方法必須實現一個Listener接口的類(匿名類或內部類),感覺很麻煩,甚至吵著要Java改語法,實現一級函數,Java 8 的lambda表達式終於解決了這個問題,但是其實不用動語法,我們還有別的辦法。最簡單的想法,如果Java有函數指針,這個問題就好解決了,不過,雖然Java沒有函數指針,卻能反射,我們一樣可以實現類似函數指針的功能。
ActionHelper用於javafx,其他場景類推
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
public class ActionHelper {
public static EventHandler<ActionEvent> handle(Object obj,String methodName,Object... param){
return new Action(obj,methodName,param);
}
private static class Action implements EventHandler<ActionEvent>{
private Object obj;
private String methodName;
private Class<?>[] clazz;
private Object[] param;
public Action(Object obj,String methodName,Object... param){
this.obj = obj;
if(param.length>0){
clazz = new Class[1+param.length];
clazz[0] = ActionEvent.class;
for(int i=0;i<param.length;i++){
clazz[1+i] = param[i].getClass();
}
this.param = new Object[1+param.length];
for(int i=0;i<param.length;i++){
this.param[1+i] = param[i];
}
}else{
clazz = new Class[1];
clazz[0] = ActionEvent.class;
this.param = new Object[1];
}
this.methodName = methodName;
}
@Override
public void handle(ActionEvent event) {
try {
Method method = obj.getClass().getDeclaredMethod(methodName, clazz);
if(method != null){
method.setAccessible(true);
param[0] = event;
method.invoke(obj, param);
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
//以下為使用的代碼片段,javafx的右鍵菜單
ContextMenu ctxMenu = new ContextMenu();
MenuItem mitem = new MenuItem("查看頁面");
mitem.setOnAction(ActionHelper.handle(this, "viewPage"));
ctxMenu.getItems().add(mitem);
private void viewPage(ActionEvent event){
//do some thing
}