Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

java - Why do I have the wrong number of arguments when calling main through reflection?

I have a Class object and I want to invoke a static method. I have the following code.

Method m = cls.getMethod("main", String[].class);
System.out.println(m.getParameterTypes().length);
System.out.println(Arrays.toString(m.getParameterTypes()));
System.out.println(m.getName());
m.invoke(null, new String[]{});

This prints:

1
[class [Ljava.lang.String;]
main

But then it then it throws:

IllegalArgumentException: wrong number of arguments

What am I overlooking here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You will have to use

m.invoke(null, (Object)new String[]{});

The invoke(Object, Object...) method accepts a Object.... (Correction) The String[] array passed is used as that Object[] and is empty, so it has no elements to pass to your method invocation. By casting it to Object, you are saying this is the only element in the wrapping Object[].

This is because of array covariance. You can do

public static void method(Object[] a) {}
...
method(new String[] {});

Because a String[] is a Object[].

System.out.println(new String[]{} instanceof Object[]); // returns true

Alternatively, you can wrap your String[] in an Object[]

m.invoke(null, new Object[]{new String[]{}});

The method will then use the elements in the Object[] as arguments for your method invocation.

Careful with the StackOverflowError of calling main(..).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...