【问题标题】:Using Java Constructor.newInstance(args) , why the "wrong number of args" error?使用 Java Constructor.newInstance(args) ,为什么会出现“args 数量错误”的错误?
【发布时间】:2011-07-24 00:59:25
【问题描述】:

为什么会失败并出现错误:

Args are: -normi -nosplash
Exception in thread "main" java.lang.IllegalArgumentException: wrong 
     number of arguments
    at sun.reflect.NativeConstructorAccessorImpl
    .newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl
    .newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl
    .newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at TSStack.main(TSStack.java:14)

代码如下:

public static void main(String args[]) throws Exception {
    System.out.println("Args are: " + args[0]+ " " + args[1] );
        try {
            Constructor<Site> c = Site.class.getDeclaredConstructor();
            c.setAccessible(true); // use reflection to get access to  
                                      //this private constructor
            c.newInstance( (Object[])args );
          } catch (InvocationTargetException x) {
            x.printStackTrace();
          } catch (NoSuchMethodException x) {
            x.printStackTrace();
          } catch (InstantiationException x) {
            x.printStackTrace();
          } catch (IllegalAccessException x) {
            x.printStackTrace();
          }     
}

【问题讨论】:

  • 可爱 - 你试图捕捉一大堆异常,但最终还是错过了这个。

标签: java class instance


【解决方案1】:

当你有这条线时:

Site.class.getDeclaredConstructor();

您将返回一个不接受参数的Site 类的构造函数,因为getDeclaredConstructor 是一个可变参数函数,它接受描述参数类型的Class&lt;?&gt; 对象列表作为参数。由于您没有列出任何内容,因此您将返回一个空构造函数。

但是,您然后尝试通过调用来创建对象

c.newInstance( (Object[])args );

这会尝试传入args 作为参数。除非args 为空,否则这将导致问题,因为您明确要求使用无参数构造函数。

编辑:由于您正在寻找的构造函数(基于您的上述评论)想要接受可变数量的Strings 作为参数,因此您想要寻找构造函数那(我相信)将Strings 的数组作为其参数,因为内部可变参数函数是使用数组实现的。你可以这样做:

Constructor<Site> c = Site.class.getDeclaredConstructor(String[].class);
c.setAccessible(true); // use reflection to get access to this private constructor
c.newInstance( (Object[])args );

更重要的是,你为什么要使用反射?写起来更快、更干净、更安全

new Site(args);

这允许 Java 静态验证代码的安全性。

希望这会有所帮助!

【讨论】:

  • 不能调用“new Site(args),因为唯一的构造函数是私有的,它接受零参数。
  • @djangofan- 那么,出于好奇,你为什么要向它传递一组参数?
【解决方案2】:

Site.class.getDeclaredConstructor() 将返回不带参数的默认构造函数,因此您必须向它传递一个空的参数数组,这在您的示例中不是这种情况(否则您将在第一行使用System.out.println() 失败)。

【讨论】:

  • 有问题的构造函数应该能够接受可变数量的参数,那么为什么它不允许我传递完整的参数列表呢?这对我来说是个谜。
  • @djangofan- 你应该尝试获取一个以String[] 作为参数的构造函数,然后;请参阅我的帖子了解如何执行此操作。
  • @djangofan 它确实需要可变数量的参数,在您的情况下为 0。如果您有一个采用String[] 的构造函数,那么您应该寻找它,而不是空参数。
  • 是的,这就是问题所在。谢谢。
猜你喜欢
  • 2020-07-25
  • 2018-01-10
  • 1970-01-01
  • 1970-01-01
  • 2013-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多