views:

204

answers:

1

I'm trying to invoke a method that takes a super class as a parameter with subclasses in the instance.

public String methodtobeinvoked(Collection<String> collection);

Now if invoke via

List<String> list = new ArrayList();
String methodName = "methodtobeinvoked";
...
method = someObject.getMethod(methodName,new Object[]{list});

It will fail with a no such method Exception

SomeObject.methodtobeinvoked(java.util.ArrayList);

Even though a method that can take the parameter exists.

Any thoughts on the best way to get around this?

+4  A: 

You need to specify parameter types in getMethod() invocation:

method = someObject.getMethod("methodtobeinvoked", Collection.class);

Object array is unnecessary; java 1.5 supports varargs.

Update (based on comments)

So you need to do something like:

Method[] methods = myObject.getClass().getMethods();
for (Method method : methods) {
  if (!method.getName().equals("methodtobeinvoked")) continue;
  Class[] methodParameters = method.getParameterTypes();
  if (methodParameters.length!=1) continue; // ignore methods with wrong number of arguments
  if (methodParameters[0].isAssignableFrom(myArgument.class)) {
    method.invoke(myObject, myArgument);
  }
}

The above only checks public methods with a single argument; update as needed.

ChssPly76
The point of the invocation is that I want to be able to call the a method that is also specified on the fly. ie I don't necessarily no the param type. method = someObject.getMethod(variableForMethodName, instanceOfsomeParameter);
Sheldon Ross
That's simply not how reflection works.
Michael Borgwardt
@Sheldon - if you don't know parameter type(s), what do you know? Just the method name? In that case you can use `Class.getMethods()` to return **all** public methods of the class in question, loop through them manually and invoke the one you need. Be aware, though, that if you don't know the parameter types you will not be able to distinguish between overloaded methods (e.g. methods that have the same name but different arguments)
ChssPly76
I think it was addressed at my comment, either way its unhelpful. I suppose I could just create a look-up table or some such, but I was hoping for a elegant solution that would allow me to find methods that would work for a given parameter type. Is there any way to tell what super classes an object inherits from?
Sheldon Ross
@Sheldon, sure. Given an instance of an object, you can call o.getClasss().getSuperclass()
Yishai
Well, the method is the same whether I pass it a List, Set, or whatever else uses the collection interface. I suppose I should just manually overload the method x number of times.
Sheldon Ross