启动java程序的main方法的参数是一个字符数组,即public static void main(String args[]),通过反射方式来调用main方法遇到的问题以及解决方案:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test3 {
/**
* @param args
* @throws NoSuchMethodException
* @throws SecurityException
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, ClassNotFoundException {
// TODO Auto-generated method stub
String str=args[0];
Method m=Class.forName(str).getMethod("main", String[].class);
m.invoke(null, new Object[]{new String[]{"111","222","333"}});//静态方法调用前面传入空值即可
//这里注意jdk1.5有了自动拆箱功能如果你后面是一个数组,它会自动将数组拆开,所以你要手动把String数组包上
//拆的时候,剩下了string数组
}
}除了上述代码的处理方案外,还有一种方案,即把整个数组当做Object使用,这时调用代码可改为:m.invoke(null, (Object)new String[]{"111","222","333"});这时的jdk将其拆开以后正好是一个String数组。

567

被折叠的 条评论
为什么被折叠?



