当参数类型为 Object[] 时,通过反射调用方法 [英] Call method via reflection when argument is of type Object[]

查看:43
本文介绍了当参数类型为 Object[] 时,通过反射调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用反射来调用 在运行时动态构造的类:

I am using reflection to call a method on a class that is dynamically constructed at runtime:

public String createJDBCProvider(Object[] args)

方法如下:

Method m = adminTask.getClass().getMethod("createJDBCProvider", Object[].class);
id = (String) m.invoke(adminTask, new Object[]{ "a", "b", "c" });

IDEA 警告我,我犯了因调用可变参数方法而创建的冗余数组.

IDEA warns me that I'm guilty of redundant array creation for calling varargs method.

我正在调用的方法实际上需要一个 Object[],而不是 Object ... 但我认为它们可能是等效的和可互换的,所以我继续前进.

The method I'm calling actually takes an Object[], not Object ... but they're probably equivalent and interchangeable I think, so I forge ahead.

在运行时我得到:

java.lang.IllegalArgumentException: wrong number of arguments

所以,我的 Object[] 似乎是作为一系列 Object 传递的.这是正在发生的事情吗?如果是这样,我怎样才能强迫它不这样做?

So it seems that, perhaps, my Object[] is being passed as a sequence of Objects. Is this what is happening? If so, how can I coerce it to not do so?

推荐答案

您调用方法的方式,反射认为您正在传递三个单独的参数,而不是单个数组参数.试试这个:

The way you are calling the method, the reflection thinks that you are passing three individual parameters, rather than a single array parameter. Try this:

id = (String) m.invoke(adminTask, new Object[]{ new Object[] {"a", "b", "c"} });

这篇关于当参数类型为 Object[] 时,通过反射调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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