View Javadoc

1   package serp.bytecode;
2   
3   /**
4    * Class loader that will attempt to find requested classes in a given
5    * {@link Project}.
6    *
7    * @author Abe White
8    */
9   public class BCClassLoader extends ClassLoader {
10      private Project _project = null;
11  
12      /**
13       * Constructor. Supply the project to use when looking for classes.
14       */
15      public BCClassLoader(Project project) {
16          _project = project;
17      }
18  
19      /**
20       * Constructor. Supply the project to use when looking for classes.
21       *
22       * @param parent the parent classoader
23       */
24      public BCClassLoader(Project project, ClassLoader loader) {
25          super(loader);
26          _project = project;
27      }
28  
29      /**
30       * Return this class loader's project.
31       */
32      public Project getProject() {
33          return _project;
34      }
35  
36      protected Class findClass(String name) throws ClassNotFoundException {
37          byte[] bytes;
38          try {
39              BCClass type;
40              if (!_project.containsClass(name))
41                  type = createClass(name);
42              else
43                  type = _project.loadClass(name);
44              if (type == null)
45                  throw new ClassNotFoundException(name);
46              bytes = type.toByteArray();
47          } catch (RuntimeException re) {
48              throw new ClassNotFoundException(re.toString());
49          }
50          return defineClass(name, bytes, 0, bytes.length);
51      }
52  
53      /**
54       * Override this method if unfound classes should be created on-the-fly.
55       * Returns null by default.
56       */
57      protected BCClass createClass(String name) {
58          return null;
59      }
60  }