编写了一个ClassLoader类,把E:\\helloworld.jar(这个jar中包含test.HelloWorld类)加入到classpath中,然后invoke() “test.Hello类”中的main函数,这个main函数依赖helloworld.jar中的方法
//ClassLoader.java public class ClassLoader { public static void main(String[] args) throws Throwable{ Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("Hello!"); } }); ArrayList<URL> classPath = new ArrayList<URL>(); classPath.add(new File("E:\\helloworld.jar" + "/").toURL()); URLClassLoader loader = new URLClassLoader(classPath.toArray(new URL[0])); Thread.currentThread().setContextClassLoader(loader); Class<?> mainClass = Class.forName("test.Hello", true, loader); Method main = mainClass.getMethod("main", new Class[] { Array .newInstance(String.class, 0).getClass() }); String[] newArgs = Arrays.asList(args).subList(0, args.length) .toArray(new String[0]); try { main.invoke(null, new Object[] { newArgs }); } catch (InvocationTargetException e) { throw e.getTargetException(); } } }
//Hello.java package test; public class Hello { public static void main(String[] args) { // TODO Auto-generated method stub test.HelloWorld.print(); } }
//HelloWorld.class/helloworld.jar package test; public class HelloWorld { public static void print() { // TODO Auto-generated method stub System.out.println("Hello World!"); } }
在eclipse中可以运行,因为我将helloworld.jar引入工程。在命令行下运行时就报NoClassDefFoundError异常
感谢解答:-)