2009-10-26 85 views
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); 

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

有没有想过解决这个问题的最佳方法?

+1

无需重载;请看看我的更新。 – ChssPly76

回答

4

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

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

Object数组是不必要的; 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); 
    } 
} 

以上仅检查公共方法带一个参数;根据需要更新。

+0

调用的要点是我希望能够调用一个即时指定的方法。即我不一定没有参数类型。 method = someObject.getMethod(variableForMethodName,instanceOfsomeParameter); –

+1

这根本不是反射如何工作。 –

+1

@Sheldon - 如果你不知道参数类型,你知道什么?只是方法名称?在这种情况下,你可以使用'Class.getMethods()'返回所有类的公有方法,手动循环并调用你需要的。但请注意,如果您不知道参数类型,您将无法区分重载的方法(例如,具有相同名称但参数不同的方法) – ChssPly76