为什么通过反射调用main时参数个数错误? [英] Why do I have the wrong number of arguments when calling main through reflection?

查看:34
本文介绍了为什么通过反射调用main时参数个数错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Class对象,我想调用一个静态方法.我有以下代码.

I have a Class object and I want to invoke a static method. I have the following code.

Method m = cls.getMethod("main", String[].class);
System.out.println(m.getParameterTypes().length);
System.out.println(Arrays.toString(m.getParameterTypes()));
System.out.println(m.getName());
m.invoke(null, new String[]{});

此打印:

1
[class [Ljava.lang.String;]
main

但是随后它抛出:

IllegalArgumentException: wrong number of arguments

我在这里俯瞰什么?

推荐答案

您将不得不使用

m.invoke(null, (Object)new String[]{});

The invoke(Object, Object...) method accepts a Object.... (Correction) The String[] array passed is used as that Object[] and is empty, so it has no elements to pass to your method invocation. By casting it to Object, you are saying this is the only element in the wrapping Object[].

这是因为数组协方差.你可以做

This is because of array covariance. You can do

public static void method(Object[] a) {}
...
method(new String[] {});

因为 String [] Object [] .

System.out.println(new String[]{} instanceof Object[]); // returns true

或者,您也可以将 String [] 包裹在 Object []

Alternatively, you can wrap your String[] in an Object[]

m.invoke(null, new Object[]{new String[]{}});

然后,该方法将使用 Object [] 中的元素作为方法调用的参数.

The method will then use the elements in the Object[] as arguments for your method invocation.

注意调用 main(..).

这篇关于为什么通过反射调用main时参数个数错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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