Sheldon Ross
Sheldon Ross

Reputation: 5544

How to invoke a method with a superclass

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?

Upvotes: 0

Views: 787

Answers (1)

ChssPly76
ChssPly76

Reputation: 100706

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.

Upvotes: 4

Related Questions