0

我正在尝试调用一个方法,该方法将超类作为参数,实例中有子类。

public String methodtobeinvoked(Collection<String> collection);

现在如果通过调用

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

如果没有这样的方法,它将失败 异常

SomeObject.methodtobeinvoked(java.util.ArrayList);

即使存在可以接受参数的方法。

关于解决此问题的最佳方法的任何想法?

4

1 回答 1

4

您需要在调用中指定参数类型:getMethod()

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

对象数组是不必要的;java 1.5 支持可变参数。

更新(基于评论)

因此,您需要执行以下操作:

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);
  }
}

以上仅检查具有单个参数的公共方法;根据需要更新。

于 2009-10-26T22:21:33.470 回答