gpt4 book ai didi

java - 使用 Java Constructor.newInstance(args) ,为什么会出现 "wrong number of args"错误?

转载 作者:行者123 更新时间:2023-12-01 07:39:38 26 4
gpt4 key购买 nike

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

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

最佳答案

当你有这一行时:

Site.class.getDeclaredConstructor();

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

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

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

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

编辑:由于您正在寻找的构造函数(根据您的上述评论)想要接受可变数量的 String s 作为参数,您想要寻找一个(我相信)接受 String 数组的构造函数s 作为其参数,因为内部可变参数函数是使用数组实现的。您可以按如下方式执行此操作:

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 静态验证代码的安全性。

希望这有帮助!

关于java - 使用 Java Constructor.newInstance(args) ,为什么会出现 "wrong number of args"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6804309/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com