它看起來像沒有辦法動態地添加方法。但是你可以用方法的列表或者像哈希準備類:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
public class GenericClass {
private HashMap<String, Method> methodMap = new HashMap<String, Method>();
public Object call(String methodName,Object ...args)
throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method method = methodMap.get(methodName);
return method.invoke(null, args);
}
public void add(String name,Method method){
if(Modifier.isStatic(method.getModifiers()))
methodMap.put(name, method);
}
public static void main(String[] args) {
try {
GenericClass task = new GenericClass();
task.add("Name",Object.class.getMethod("Name", new Class<?>[0]));
} catch (NoSuchMethodException | SecurityException e) {
e.printStackTrace();
}
}
}
比,使用反射可以設置或取消的屬性。
這將是真棒,如果它可以! :) – Nicholas
是的,這是可能的。檢查此問題:http://stackoverflow.com/questions/17323500/aspect-weaving-at-runtime –
據我所知,aop可以用於像日誌記錄的事情,但OP要求框架識別某類處理的類基於一種方法的存在。換句話說,可以使用AOP添加方法簽名嗎? – Quaternion