views:

200

answers:

3

Or, in other words, what is 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 the methods, I just want to use them as objects! What to do?

+6  A: 

this works, I can't help but wondering, what you're doing with this?

new Method[] { 
  Vector.class.getMethod("add", Object.class), 
  Vector.class.getMethod("remove", Object.class) 
};
Allain Lalonde
I was very confused of what the question was ... :S
OscarRyz
A: 

First of all, you're making up syntax here. There's no "Vector.add()" in my javadocs.

You can do this:


Method [] methods = Vector.class.getMethods();

but you can't execute those methods. No closures or function objects here.

duffymo
Actually, the methods CAN be executed. No closures I agree.
OscarRyz
Ah! It's "invoke". I was looking for "execute" in the javadocs and didn't see it. Thank you for the correction.
duffymo
"No Vector.add()"? public synchronized boolean add(E e) { @since 1.2, might be time to update your JVM. :)
Cowan
Not as a static method. I was looking at JDK 6 docs.
duffymo
A: 

That works :)

I'm using this to instantiate a variable number of "stacked" loops (loop within a loop within a loop).

There is a static method to which you pass the starting index, limit, Object to invoke the methods with, and finally an array of methods and an array of arguments.

EDIT: Rough code - took me 3 minutes to write, so there's probably something very bad lurking in there, but the general idea is obvious, I think.

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 this whole thing for - I'm just tinkering around with a way to do permutations where the number of elements is less than the number of positions. I've ran into problems trying to define a variable number of loops (which depends on the number of positions), so decided to circumvent it with this.

Alexander
In Java, the idiomatic way to pass around a function as an object is to define an interface with an execute method and then implement that interface, often with an anonymous class. It's clunkier than functional languages, but it's also typesafe, unlike your method.
Dave Ray
See for instance Collections.max(Collection,Comparator).
Tom Hawtin - tackline