Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/385.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在方法调用期间将数组作为参数传递时发生IllegalArgumentException_Java_Exception_Reflection_Parameters - Fatal编程技术网

Java 在方法调用期间将数组作为参数传递时发生IllegalArgumentException

Java 在方法调用期间将数组作为参数传递时发生IllegalArgumentException,java,exception,reflection,parameters,Java,Exception,Reflection,Parameters,我一定错过了一些非常基本的东西。当我试图在方法调用期间传递任何类型的数组时,我会得到一个错误。然而,当我做它正常工作 这是失败的完整代码 import java.lang.reflect.Method; public class Main { public static void main(String[] args) throws Exception { // Normal MyClass.sayHello(new String[] {"StackO

我一定错过了一些非常基本的东西。当我试图在方法调用期间传递任何类型的数组时,我会得到一个错误。然而,当我做它正常工作

这是失败的完整代码

import java.lang.reflect.Method;

public class Main {
    public static void main(String[] args) throws Exception {

        // Normal
        MyClass.sayHello(new String[] {"StackOverflow"});

        // Reflection
        Method m = MyClass.class.getMethod("sayHello", String[].class);
        m.invoke(null, new String[]{"StackOverflow"});
    }

    static class MyClass {
        public static void sayHello(String[] args) {
            System.out.println("Hello " + args[0]);
        }
    }
}
引发的异常

Exception in thread "main" java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at Main.main(Main.java:11)

String…
也不起作用。

问题是
调用的第二个参数是一个参数数组-您只指定了一个参数

在大多数情况下,这可以作为
方法的第二个参数。invoke
是一个varargs参数,但由于您的参数已经是与
对象[]
兼容的数组,编译器不会创建包装器数组。我希望您得到如下编译时警告:

Main.java:11: warning: non-varargs call of varargs method with inexact argument type for
                       last parameter;
        m.invoke(null, new String[]{"StackOverflow"});
                       ^
  cast to Object for a varargs call
  cast to Object[] for a non-varargs call and to suppress this warning
您可以显式创建一个包装参数的数组,或者将参数强制转换为
对象
,以便编译器需要包装它自己:

// Creates the wrapper array explicitly
m.invoke(null, new Object[] { new String[] { "StackOverflow" } });


是的,我收到了同样的警告。Java为什么需要一个数组参数数组,这是毫无道理的,但它是可行的。谢谢@TomTom:这很有道理:它需要一个数组,因为可以有多个参数。该数组的唯一元素本身就是数组,因为该方法的参数是数组。尝试向方法中添加另一个参数,这样会更有意义。今后,千万不要忽视警告:)@JonSkeet它只是发出了咔嗒声。它需要一个
字符串[]
作为参数,同时还需要一个数组作为参数的参数。谢谢,我不会的!我刚接触瓦拉格斯:)
// Compiler creates the wrapper array because the argument type is just Object
m.invoke(null, (Object) new String[] { "StackOverflow" });