我们作业要求:The purpose of this project is to demonstrate the technique for passing function names (i.e., method names) as parameters to other functions/methods in Java.Note that you should use abstract methods to provide functional, i.e. method types.http://www.coitweb.uncc.edu/~revesz/Fall2012/NewFix.html
那这个例子呢?:public void setAllComponents(Component[] myComponentArray, Method myMethod) {
for (Component leaf : myComponentArray) {
if (leaf instanceof Container) { //recursive call if Container
Container node = (Container) leaf;
setAllComponents(node.getComponents(), myMethod);
} //end if node
myMethod(leaf);
} //end looping through components
}
invoked such as:setAllComponents(this.getComponents(), changeColor());
setAllComponents(this.getComponents(), changeSize());
return o.getClass().getDeclaredMethod(method, paramTypes).invoke(o, params);
}
public String testMethod(String s){
System.out.println(s);
return s + "return";
}
public static void main(String[] args) throws IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Invoker inv = new Invoker();
String s = "toto";
Class[] c = {s.getClass()};
Object[] o = {s};
System.out.println(Invoker.invoke(inv, "testMethod", c, o));
}
}
或者可以传递一个Method对象过去..