Search code examples
javamethodssubclassinvokesuperclass

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?


Solution

  • 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.