Docjar: A Java Source and Docuemnt Enginecom.*    java.*    javax.*    org.*    all    new    plug-in

Quick Search    Search Deep

Source code: com/arranger/jarl/clazz/JarlClassLoader.java


1   package com.arranger.jarl.clazz;
2   
3   
4   
5   import com.arranger.jarl.util.StringTools;
6   import com.arranger.jarl.util.IOUtil;
7   
8   import java.util.Map;
9   import java.util.HashMap;
10  import java.io.IOException;
11  
12  /**
13   * WebClassLoader created on Jan 17, 2003
14   */
15  public class JarlClassLoader extends ClassLoader {
16  
17  
18      protected String m_rootDirectory;
19      protected Map m_loadedClasses = new HashMap();
20      protected String m_prefix;
21  
22      /**
23       * @param root is the root file system folder to look for class files
24       * @param prefix is the class prefix is the required prefix for this class loader to use, otherwise it delegates to the base implementation
25       */
26      public JarlClassLoader(String root, String prefix) {
27          m_rootDirectory = com.arranger.jarl.util.StringTools.normalizePath(root);
28          m_prefix = prefix;
29      }
30  
31      /**
32       *  This is the main api to call.  Pass in the className
33       */
34      public Class findClass(String className) throws ClassNotFoundException {
35          if (m_prefix == null || !className.startsWith(m_prefix)) {
36              return super.findClass(className);
37          }
38  
39          Class clazz = (Class)m_loadedClasses.get(className);
40          if (clazz == null) {
41              try {
42                  byte [] classBytes = loadClassData(className);
43                  clazz = defineClass(className, classBytes, 0, classBytes.length);
44                  m_loadedClasses.put(className, clazz);
45              } catch(IOException e) {
46                  throw new ClassNotFoundException(e.getMessage(), e);
47              }
48          }
49          return clazz;
50      }
51  
52      protected byte[] loadClassData(String className) throws IOException {
53          String classLocation = StringTools.appendPath(m_rootDirectory,
54                                 className.replace('.', '/')) +
55                                 ".class";
56  
57          return IOUtil.toByteArray(classLocation);
58      }
59  
60      /**
61       * This is called when a Class loaded with findClass has internal objects in it.
62       */
63      protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException {
64          if (m_prefix == null || !name.startsWith(m_prefix)) {
65              return super.loadClass(name, resolve);
66          }
67          Class clazz = findClass(name);
68          if (clazz == null) {
69              return super.loadClass(name, resolve);
70          }
71  
72          if (resolve) {
73              resolveClass(clazz);
74          }
75          return clazz;
76      }
77  }