1 6 7 package org.jfox.ioc.classloader; 8 9 import java.io.File ; 10 import java.net.URL ; 11 import java.net.URLClassLoader ; 12 import java.util.ArrayList ; 13 import java.util.List ; 14 import java.util.Map ; 15 import java.util.WeakHashMap ; 16 17 import org.jfox.ioc.Constants; 18 import org.jfox.ioc.logger.Logger; 19 import org.jfox.ioc.util.FileFilters; 20 import org.jfox.ioc.util.Files; 21 22 27 28 public class ClassLoaderRepository extends URLClassLoader { 29 private Logger logger = Logger.getLogger(ClassLoaderRepository.class 30 .getName()); 31 32 35 private Map classes = new WeakHashMap (); 36 37 private final static String COMMON_LIBS = System.getProperty(Constants.JFOXCO_COMMON_LIBS, 38 System.getProperty(Constants.JFOXCO_HOME) + "/common"); 39 40 43 private List <LocalClassLoader> localCLs = new ArrayList <LocalClassLoader>(); 44 45 50 52 public ClassLoaderRepository(URL [] urls, ClassLoader parent) { 53 super(urls, parent); 54 loadExternalLibs(); 55 } 56 57 60 private void loadExternalLibs() { 61 File libDir = new File (COMMON_LIBS); 62 if(!libDir.exists() || libDir.isFile()) 63 return; 64 List jarFiles = Files.listFiles(libDir, FileFilters 65 .suffixFileFilter(new String []{"jar", "zip"})); 66 for(int i = 0; i < jarFiles.size(); i++) { 67 File file = (File ) jarFiles.get(i); 68 try { 69 addURL(file.toURL()); 70 } 71 catch(Exception e) { 72 e.printStackTrace(); 73 } 74 } 75 } 76 77 public URL [] getURLs() { 78 return super.getURLs(); 79 } 80 81 synchronized void addLocalCL(LocalClassLoader localCL) { 82 if(!localCLs.contains(localCL)) { 83 localCLs.add(localCL); 84 } 85 } 86 87 public void removeLocalCL(LocalClassLoader localCL) { 88 localCLs.remove(localCL); 89 } 90 91 96 public void addURL(URL url) { 97 logger.debug("add class path " + url.toString()); 98 super.addURL(url); 99 } 100 101 107 109 111 121 protected synchronized Class <?> loadClass(String name, boolean resolve) throws ClassNotFoundException { 122 try { 123 return super.loadClass(name,resolve); 124 } 125 catch(ClassNotFoundException e) { 126 try { 127 return loadClassCached(name); 128 } 129 catch(ClassNotFoundException e1) { 130 131 } 132 } 133 throw new ClassNotFoundException (name); 134 135 } 136 137 141 146 147 synchronized void cacheClass(Class clz) { 148 if(!classes.containsKey(clz.getName())) { 149 logger.debug("cache " + clz + ", classloader is " 150 + clz.getClassLoader()); 151 classes.put(clz.getName(), clz); 152 } 153 } 154 155 162 synchronized Class loadClassCached(String name) throws ClassNotFoundException { 163 if(!classes.containsKey(name)) { 164 throw new ClassNotFoundException (name); 165 } 166 return (Class ) classes.get(name); 167 } 168 169 170 173 188 189 192 210 211 237 238 public static void main(String [] args) { 239 240 } 241 } | Popular Tags |