views:

538

answers:

3

I need to invoke a method without knowing a priori what will the amount of arguments be.
I've tried using the member Method.invoke(Object, Object...) passing as second parameter an array of objects which contains my arguments, however that did not really work.
Is there a way to do what I'm after?

A: 

Once you have the Method object, you can use getParameterTypes() to determine this. From the JavaDoc:

Returns an array of Class objects that represent the formal parameter types, in declaration order, of the method represented by this Method object. Returns an array of length 0 if the underlying method takes no parameters.

Peter
+2  A: 

The way you describe it is the correct way to do it. Your argument array, however, must have the exact same number of arguments that target method has; they have to be listed in the correct order and have appropriate types. Can you post the exception stack trace you're getting and a code sample?

ChssPly76
I had a call with wrong arguments and that caused the whole thing to fail but tracing back to the call was hard.Thanks :)
emaster70
A: 

Varargs is the way. Check docs:

You use varargs when you don't know how many of a particular type of argument will be passed to the method. It's a shortcut to creating an array manually.
To use varargs, you follow the type of the last parameter by an ellipsis (three dots, ...), then a space, and the parameter name. The method can then be called with any number of that parameter, including none.

public Polygon polygonFrom(Point... corners) {
    int numberOfSides = corners.length;
    double squareOfSide1, lengthOfSide1;
    squareOfSide1 = (corners[1].x - corners[0].x)*(corners[1].x - corners[0].x) 
      + (corners[1].y - corners[0].y)*(corners[1].y - corners[0].y) ;
    lengthOfSide1 = Math.sqrt(squareOfSide1);
    // more method body code follows that creates 
    // and returns a polygon connecting the Points
}

PS. Varargs is available on Java 1.5 or later.

Thushan
You can even pass an array to the above method:Point[] p = {new Point(1,2), new Point(3,4), new Point(5,6)}; ploygonFrom(p);
Thushan