Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.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 如何调用使用反射获取数组的方法_Java_Arrays - Fatal编程技术网

Java 如何调用使用反射获取数组的方法

Java 如何调用使用反射获取数组的方法,java,arrays,Java,Arrays,考虑以下完整的Java程序 public class Reflection { static class A { public void useArray( String[] args ) { System.out.println( "Args are " + Arrays.toString( args ) ); } } public static void main( String[] args ) throws Exception

考虑以下完整的Java程序

public class Reflection
{

  static class A
  {
    public void useArray( String[] args )
    {
        System.out.println( "Args are " + Arrays.toString( args ) );
    }
  }

  public static void main( String[] args ) throws Exception
  { 
    Method m = A.class.getMethod( "useArray", String[].class );
    m.invoke( new A(), new String[] { "Hi" } );
  }

}
尝试运行此操作时,会出现错误:

Exception in thread "main" java.lang.IllegalArgumentException: argument type mismatch
如果在传递给
invoke
的数组中只使用一个字符串,而不是传递多个字符串,则会得到:

Exception in thread "main" java.lang.IllegalArgumentException: wrong number of arguments
因此,很明显,因为
invoke
的签名是:

invoke(java.lang.Object obj, java.lang.Object... args)
当我使用数组调用
invoke
时,调用被“转换”为:


如何让Java理解我确实希望我的数组被完整地传递到
invoke
中???

尝试将数组强制转换为
对象

m.invoke(new A(), (Object)new String[] { "Hi" });
必须这样做,因为array if String是对象数组的子类型,并且

invoke(java.lang.Object obj, java.lang.Object... args)
使用对象数组可以解释为在字符串数组中为方法传递参数。将其强制转换为单个对象将使varargs
将其读取为单个元素,而不是元素数组


另一种解决方案是使用单独的对象数组包装数组,如

m.invoke(new A(), new Object[]{new String[] { "Hi" }});
这样,字符串数组将不再是
invoke
的参数数组。这一次,数组外部将是带有参数的数组,这使字符串数组成为单个参数

m.invoke(new A(), new Object[]{new String[] { "Hi" }});