package pri.lee.demo;public class HelloWord { public static void main(String[] args) { for (int i = 0; i < 100; i++) { System.out.println("helloword"); } }}
import java.io.*;import java.lang.reflect.Array;import java.lang.reflect.Method;import java.net.URL;import java.net.URLClassLoader;import java.util.ArrayList;import java.util.Enumeration;import java.util.jar.JarEntry;import java.util.jar.JarFile;import java.util.jar.Manifest;/** * @Author:li * @Date:created in 2018/1/13 11:39 */public class JarTest { public static void main(String[] args) throws Exception { String fileName = "C:\\Users\\marje\\Desktop\\HelloWord.jar"; File file = new File(fileName); String mainClassName = null; JarFile jarFile; jarFile = new JarFile(fileName); //获取主类 Manifest manifest = jarFile.getManifest(); if (manifest != null) { mainClassName = manifest.getMainAttributes().getValue("Main-Class"); } jarFile.close(); if (mainClassName == null) { if (args.length < 2) { System.exit(-1); } // 如果MANIFEST.MF未设置Main-Class,则用户输入 } mainClassName = mainClassName.replaceAll("/", "."); final File workDir = File.createTempFile("unjar", "", new File(System.getProperty("user.dir"))); workDir.delete(); workDir.mkdirs(); if (!workDir.isDirectory()) { System.err.println("Mkdirs failed to create " + workDir); System.exit(-1); } unJar(file, workDir); // 设置classPath ArrayListclassPath = new ArrayList (); classPath.add(new File(workDir + "/").toURL()); classPath.add(file.toURL()); ClassLoader loader = new URLClassLoader(classPath.toArray(new URL[0])); Thread.currentThread().setContextClassLoader(loader); // 利用反射取得class和method Class mainClass = Class.forName(mainClassName, true, loader); Method main = mainClass.getMethod("main", Array .newInstance(String.class, 1).getClass()); Object ob = mainClass.newInstance(); // 运行方法 String[] a = new String[3]; main.invoke(ob, (Object) a); System.out.println(1); } public static void unJar(File jarFile, File toDir) throws IOException { JarFile jar = new JarFile(jarFile); try { Enumeration entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = (JarEntry) entries.nextElement(); if (!entry.isDirectory()) { InputStream in = jar.getInputStream(entry); try { File file = new File(toDir, entry.getName()); if (!file.getParentFile().mkdirs()) { if (!file.getParentFile().isDirectory()) { throw new IOException( "Mkdirs failed to create " + file.getParentFile() .toString()); } } OutputStream out = new FileOutputStream(file); try { byte[] buffer = new byte[8192]; int i; while ((i = in.read(buffer)) != -1) { out.write(buffer, 0, i); } } finally { out.close(); } } finally { in.close(); } } } } finally { jar.close(); } }}