gpt4 book ai didi

java - 如何使用父类(super class)调用方法

转载 作者:行者123 更新时间:2023-12-01 19:25:08 24 4
gpt4 key购买 nike

我正在尝试调用一个方法,该方法将父类(super class)作为参数,并在实例中包含子类。

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

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

关于解决这个问题的最佳方法有什么想法吗?

最佳答案

您需要在 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);
}
}

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

关于java - 如何使用父类(super class)调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1627660/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com