如何使用超类调用方法

时间:2009-10-26 22:18:38

标签: java methods subclass invoke superclass

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

public String methodtobeinvoked(Collection<String> collection);

现在如果通过

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

没有这样的方法Exception

会失败
SomeObject.methodtobeinvoked(java.util.ArrayList);

即使存在可以获取参数的方法。

有关解决这个问题的最佳方法吗?

1 个答案:

答案 0 :(得分:4)

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

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

对象数组是不必要的; java 1.5支持varargs。

更新(根据评论)

所以你需要做一些事情:

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

以上仅使用单个参数检查 public 方法;根据需要更新。