通过该JarManagerUtil实现对指定jar包类的全量加载初始化实例,并获取其对应的class实例集合和对于jar包制定文件数据流等,具体如下所示
import java.io.File;@b@import java.io.InputStream;@b@import java.net.URL;@b@import java.net.URLClassLoader;@b@import java.util.ArrayList;@b@import java.util.Enumeration;@b@import java.util.HashMap;@b@import java.util.List;@b@import java.util.Map;@b@import java.util.jar.JarEntry;@b@import java.util.jar.JarFile;@b@@b@public class JarManagerUtil{@b@ @b@ public static Map<String, Class<?>> jarClasses = new HashMap();@b@@b@ public static void loadJar(File file){@b@ try {@b@ if (file == null)@b@ return;@b@ URLClassLoader loader = new URLClassLoader(new URL[] {new URL("file:" + file.getAbsolutePath()) }, Thread.currentThread().getContextClassLoader());@b@ JarFile jarFile = new JarFile(file);@b@ Enumeration enum1 = jarFile.entries();@b@ while (enum1.hasMoreElements()) {@b@ JarEntry entry = (JarEntry)enum1.nextElement();@b@ if (entry.isDirectory())@b@ continue;@b@ String jar = entry.getName();@b@ if (jar.endsWith(".class")) {@b@ String clzname = jar.substring(0, jar.lastIndexOf(".class")).replace('/', '.');@b@ Class clz = loader.loadClass(clzname);@b@ jarClasses.put(clzname, clz);@b@ }@b@ }@b@ if (jarFile == null) return; @b@ jarFile.close();@b@ } catch (Exception e) {@b@ e.printStackTrace();@b@ }@b@ }@b@@b@ public static List<Class<?>> getClazzInstances(File file){@b@ try {@b@ if (file == null)@b@ return null;@b@ URLClassLoader loader = new URLClassLoader(new URL[] { @b@ new URL("file:" + file.getAbsolutePath()) }, Thread.currentThread()@b@ .getContextClassLoader());@b@ List classinstances = new ArrayList();@b@ JarFile jarFile = new JarFile(file);@b@ Enumeration enum1 = jarFile.entries();@b@ while (enum1.hasMoreElements()) {@b@ JarEntry entry = (JarEntry)enum1.nextElement();@b@ if (entry.isDirectory())@b@ continue;@b@ String jar = entry.getName();@b@ if (jar.endsWith(".class")) {@b@ String clzname = jar.substring(0, jar.lastIndexOf(".class")).replace('/', '.');@b@ Class clz = loader.loadClass(clzname);@b@ classinstances.add(clz);@b@ jarClasses.put(clzname, clz);@b@ }@b@ }@b@ if (jarFile != null) jarFile.close();@b@ return classinstances;@b@ } catch (Exception e) {@b@ e.printStackTrace();@b@ }@b@ return null;@b@ }@b@@b@ public static InputStream getInputStream(File file, String suffix){@b@ InputStream is = null;@b@ try {@b@ if (file == null)@b@ return null;@b@ JarFile jarFile = new JarFile(file);@b@ Enumeration enum1 = jarFile.entries();@b@ while (enum1.hasMoreElements()) {@b@ JarEntry entry = (JarEntry)enum1.nextElement();@b@ if (entry.isDirectory())@b@ continue;@b@ String jar = entry.getName();@b@ if (jar.endsWith(suffix))@b@ is = jarFile.getInputStream(entry);@b@@b@ }@b@@b@ return is;@b@ } catch (Exception e) {@b@ }@b@ return is;@b@ }@b@@b@ public static boolean existsSameJar(String path, String filename){@b@ File file = new File(path);@b@ String jarPath = file.getPath() + "/" + filename;@b@ File jar = new File(jarPath);@b@ return jar.exists();@b@ }@b@@b@@b@}