考虑以下代码,
public class StartUp {
public StartUp(String[] test){}
public static void main(String[] args) throws Exception{
Constructor cd = StartUp.class.getConstructor(String[].class);
System.out.println(cd.newInstance(new String[]{}).toString());
}
}
它出了什么问题?我得到以下例外:
线程“main”中的异常java.lang.IllegalArgumentException:参数数量错误 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) 在com.test.StartUp.main(StartUp.java:10)
答案 0 :(得分:23)
您的String[]
被隐式转换为Object[]
并被视为一个空数组参数,而不是作为一个空数组的单个参数。试试这个:
Object arg = new String[0];
System.out.println(cd.newInstance(arg).toString());
或
System.out.println(cd.newInstance(((Object)new String[0]).toString());
甚至避免编译器必须为你创建数组:
System.out.println(cd.newInstance(new Object[] { new String[0] }).toString());
基本上这是varargs处理和数组协方差的混合:(
答案 1 :(得分:-1)
您可以使用dp4j详细选项来回答您的问题,并获取所需的正确反映代码:
$ vim ReflectedAcces.java
class StartUp {
private StartUp(String[] test){}
}
public class ReflectedAcces{
@com.dp4j.InjectReflection
public static void main(String[] args) throws Exception{
StartUp su = new StartUp(new String[]{});
System.out.println(su.toString());
}
}
$ javac -cp dp4j-1.0-jar-with-dependencies.jar -Averbose=true ReflectedAcces.java
...
ReflectedAcces.java:10: Note:
class StartUp {
private StartUp(String[] test) {
}
}
public class ReflectedAcces {
public ReflectedAcces() {
super();
}
@com.dp4j.InjectReflection()
public static void main(String[] args) java.lang.ClassNotFoundException, java.lang.NoSuchFieldException, java.lang.IllegalAccessException, java.lang.NoSuchMethodException, java.lang.reflect.InvocationTargetException, java.lang.InstantiationException {
final java.lang.reflect.Constructor startUpConstructor = Class.forName("StartUp").getDeclaredConstructor(.java.lang.String[].class);
startUpConstructor.setAccessible(true);
StartUp su = (.StartUp)startUpConstructor.newInstance(new .java.lang.Object[1][]{new String[]{}});
System.out.println(su.toString());
}
}