How do I refer to method objects in Java?
Or, in other words, what's wrong with something like -
new Method[] {Vector.add(), Vector.remove()}
Eclipse keeps telling me that I need arguments. But I obviously don't want to call methods, I just want to use them as objects! What to do?
It works, I can't help but wonder what are you doing about it?
new Method[] {
Vector.class.getMethod("add", Object.class),
Vector.class.getMethod("remove", Object.class)
};
First of all, you compose the syntax here. There is no "Vector.add ()" in my javadocs.
You can do it:
Method [] methods = Vector.class.getMethods();
but you cannot follow these methods. There are no closures or function objects here.
It works:)
I use this to instantiate a variable number of "folded" loops (loop within loop in loop).
There is a static method with which you pass the start index, limit, Object to invoke methods with, and finally an array of methods and an array of arguments.
EDIT: Rough code - it took me 3 minutes to write, so there is probably something very bad hiding there, but the general idea is obvious I guess.
public static void loop(int start, int lessThan, Object obj, Method[] methods, Object[] args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
lastLoop++;
for(int i = start; i < lessThan; i++) {
for(int j = 0; j < methods.length; j++) {
methods[j].invoke(obj, args[j]);
}
}
}
If you're wondering what I'm using all of this for, I'm just doing a permutation where the number of items is less than the number of positions. I ran into problems trying to define a variable number of loops (which depends on the number of positions), so I decided to work around it with this.