public class Invoked {
public static void main(String[] args) {
if (args.length != 2) {
System.err.System.exit(1);
}
System.out.println("Hello, I come from OutClassFile!");
System.out.println("my name is "+args[0]);
System.out.println("my sex is "+args[1]);
}
}
運行上述類文件的主程序(Invoker.java)一般具有如下形式:
import java.lang.reflect.*;
public class Invoker {
public static void main(String[] args) {
//args[0]存儲被執(zhí)行的外部類名,本例中args[0]=“Invoked”
if (args.length != 1) {
System.err.println("Usage: java Invoker ");
System.exit(1);
}
Class[] argTypes = new Class[1];
argTypes[0] = String[].class;
try {
Method mainMethod = Class.forName(args[0]).getDeclaredMethod("main",argTypes);
Object[] argListForInvokedMain = new Object[1];
//被調(diào)用的main()方法的參數(shù)個數(shù)=1
argListForInvokedMain[0] = new String[2];
//被調(diào)用的main()方法的參數(shù)是一個長度為2的String數(shù)組
String argsToinvoked[]={"WangShuangLin","Man"};
ArgListForInvokedMain[0]= argsToinvoked;
//設置傳遞給被調(diào)用的外部類的main()方法的參數(shù)
mainMethod.invoke(null, argListForInvokedMain);
//inkoke(Object obj, Object[] args)是調(diào)用方法;
//其中obj是方法所在的對象實例; 但因為這里的main()是靜態(tài)方法,
//所以無須實例化,填上null即可;
//args是傳遞給該方法的參數(shù)。
}
catch (ClassNotFoundException ex) {
System.err.println("Class"+args[0]+"not found in classpath.");
}
catch (NoSUChMethodException ex) {
System.err.println("Class "+args[0]+" does not define public static void main(String[])");
}
catch (InvocationTargetException ex) {
System.err.println("Exception while executing "+args[0]+ ":"+ex.getTargetException());
}
catch (IllegalaccessException ex) {
System.err.println("main(String[]) in class "+args[0] + "is not public");
}
}
}
用如下的命令行運行主程序:java Invoker Invoked。新聞熱點
疑難解答