有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用Java构造函数初始化。newInstance(args),为什么会出现“args数错误”错误?

为什么会出现以下错误:

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();
          }     
}

共 (1) 个答案

  1. # 1 楼答案

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