1 26 package org.enhydra.xml.xmlc.deferredparsing; 27 28 import java.util.Collections ; 29 import java.util.HashMap ; 30 import java.util.Map ; 31 32 import org.apache.bcel.classfile.JavaClass; 33 import org.enhydra.xml.xmlc.StreamXMLCLogger; 34 import org.enhydra.xml.xmlc.XMLCLogger; 35 36 public class DynamicClassLoader extends ClassLoader 37 { 38 private ClassLoader delegateLoader = null; 39 private XMLCLogger logger = null; 40 private Map classMap; 41 42 DynamicClassLoader(ClassLoader parent) { 43 this(parent, null); 44 } 45 46 DynamicClassLoader(ClassLoader parent, XMLCLogger logger) { 47 super(parent); 48 if (logger != null) { 49 this.logger = logger; 50 } else { 51 this.logger = new StreamXMLCLogger(); 52 } 53 classMap = Collections.synchronizedMap(new HashMap ()); 54 } 55 56 60 public void setDelegate (ClassLoader delegate) { 61 delegateLoader = delegate; 62 } 63 64 67 public Class loadClass(String className) throws ClassNotFoundException { 68 Class clazz = null; 69 ClassLoader loader = null; 70 71 try { 72 if (delegateLoader != null) { 73 loader = delegateLoader; 74 } else { 75 loader = getParent(); 76 } 77 clazz = loader.loadClass(className); 78 } catch (ClassNotFoundException e) { 79 if (loader != getParent()) { 80 clazz = getParent().loadClass(className); 81 } else { 82 throw e; 83 } 84 } 85 86 return clazz; 87 } 88 89 93 private Class defineClass (JavaClass clazz) { 94 byte[] buf = clazz.getBytes(); 95 return defineClass(null, buf, 0, buf.length); 96 } 97 98 102 Class createClass(String className, String path) { 103 104 if (logger.debugEnabled()) { 105 logger.logDebug(">>>Request to create class " + className + " from document " + path); 106 } 107 108 Class clazz = (Class )classMap.get(className); 109 if (clazz == null) { 110 synchronized(classMap) { 111 clazz = (Class )classMap.get(className); 112 if (clazz == null) { 113 DynamicMLCreator dhc = new DynamicMLCreator(className, path); 114 JavaClass javaClass = dhc.create(); 115 clazz = defineClass(javaClass); 116 117 classMap.put(className, clazz); 118 } 119 } 120 } else { 121 if (logger.debugEnabled()) { 122 logger.logDebug(">>>Got class " + className + "from cache"); 123 } 124 } 125 126 return clazz; 127 } 128 129 } 130 | Popular Tags |