前几天面试的时候,被问到在Java中是否可以调用一个类中的main方法?回来测试了下,答案是可以!代码如下:
main1中调用main2的主方法
package org.fiu.test; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Main1 { /** * @param args */ public static void main(String[] args) { System.out.println("main1"); ClassLoader classLoader = Main1.class.getClassLoader(); try { Class<?> loadClass = classLoader.loadClass("org.fiu.test.Main2"); Method method = loadClass.getMethod("main", String[].class); method.invoke(null, new Object[] { new String[] {} }); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
main2类:
package org.fiu.test; public class Main2 { /** * @param args */ public static void main(String[] args) { System.out.println("main2"); } }
运行main1,打印如下:
main1 main2