如何使用超类调用方法

发布于 2024-08-09 04:27:37 字数 504 浏览 3 评论 0原文

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

public String methodtobeinvoked(Collection<String> collection);

现在,如果通过调用

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

它将会失败,并出现 no such method Exception,

SomeObject.methodtobeinvoked(java.util.ArrayList);

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

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淡淡绿茶香 2024-08-16 04:27:37

您需要在 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方法;根据需要更新。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文