Java反射:getMethod(String方法,Object [] .class)无法正常工作 [英] Java reflection: getMethod(String method, Object[].class) not working

查看:103
本文介绍了Java反射:getMethod(String方法,Object [] .class)无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

public void myMethod(Object... args) {
    System.out.println("this is myMethod");
}

public void invokeMyMethod() {
    Method s = this.getClass().getMethod("myMethod", Object[].class);
    Object[] ex = new Object[2];
    ex[0] = "hi";
    ex[1] = "there";
    s.invoke(this, ex);
}

我收到异常java.lang.IllegalArgumentException:错误的参数个数。怎么了?

I'm getting the exception java.lang.IllegalArgumentException: wrong number of arguments. What's wrong?

推荐答案

你需要调用这样的方法:

You need to call the method like this:

s.invoke(this, new Object[]{new Object[]{"hi", "there"}});

(...或在@ Jon的答案中使用替代方案。)

(... or use the alternative in @Jon's answer.)

当前代码失败的原因与Java中实现varadic方法的方式有关。基本上, T1 xxx(T2 ... args) T1 xxx(T2 [] args)的语法糖。当你调用方法时, xxx(arg1,arg2,arg3) xxx的语法糖(新的T2 [] {arg1,arg2,arg3 })

The reason your current code fails is to do with the way that varadic methods are implemented in Java. Essentially, T1 xxx(T2... args) is syntactic sugar for T1 xxx(T2[] args). And when you call the methods, xxx(arg1, arg2, arg3) is syntactic sugar for xxx(new T2[]{arg1, arg2, arg3}).

在这种情况下,您尝试使用具有相同数组基本类型的另一个varadic方法调用varadic方法,并且代码的多种可能解释。

In this case, you are trying to call a varadic method using another varadic method with the same array basetype, and there are multiple possible interpretations of the code.

当对varadic调用有两种可能的解释时,Java 假定你正在尝试使用没有看到调用版本而不是含糖版本。或者更确切地说,加糖解释用于当且仅当

When there are two possible interpretations of a varadic call, Java assumes that you are trying to use the "unsugared" version of the call instead of the "sugared" version. Or to be more precise, the "sugared" interpretation is used if and only if:


  • 的数量实际参数不等于形式参数的数量,

  • 最后一个实际参数与上一个形式参数的(数组)类型不兼容。

如果您有兴趣,可以在JLS的 15.12.4.2

If you are interested, this behaviour is specified in the JLS in section 15.12.4.2.

所以......我的解决方案通过强制非varadic解释并显式构造所需的数组来工作。 @ Jon的解决方案通过强制正确的 varadic解释来工作。

So ... my solution works by forcing the non-varadic interpretation and explicitly constructing the required array. @Jon's solution works by forcing the correct varadic interpretation.

这篇关于Java反射:getMethod(String方法,Object [] .class)无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆