01: /**************************************************************************/
02: /* N I C E */
03: /* A high-level object-oriented research language */
04: /* (c) Daniel Bonniot 2003 */
05: /* */
06: /* This program is free software; you can redistribute it and/or modify */
07: /* it under the terms of the GNU General Public License as published by */
08: /* the Free Software Foundation; either version 2 of the License, or */
09: /* (at your option) any later version. */
10: /* */
11: /**************************************************************************/package nice.tools.util;
12:
13: /**
14: A class loader that loads from a list of directories.
15:
16: @author Daniel Bonniot (bonniot@users.sourceforge.net)
17: */
18:
19: import java.io.*;
20:
21: public class DirectoryClassLoader extends java.lang.ClassLoader {
22: /**
23: * @param dirs directories to load from
24: * @param parent the parent classloader
25: */
26: public DirectoryClassLoader(File[] dirs,
27: java.lang.ClassLoader parent) {
28: super (parent);
29: this .dirs = dirs;
30: }
31:
32: private File[] dirs;
33:
34: /**
35: * This is the method where the task of class loading
36: * is delegated to our custom loader.
37: *
38: * @param name the name of the class
39: * @return the resulting <code>Class</code> object
40: * @exception ClassNotFoundException if the class could not be found
41: */
42: protected Class findClass(String name)
43: throws ClassNotFoundException {
44: String path = name.replace('.', '/') + ".class";
45:
46: for (int i = 0; i < dirs.length; i++) {
47: Class res = findClass(name, new File(dirs[i], path));
48: if (res != null)
49: return res;
50: }
51:
52: throw new ClassNotFoundException(name);
53: }
54:
55: private Class findClass(String name, File file) {
56: FileInputStream fi = null;
57:
58: try {
59: fi = new FileInputStream(file);
60: } catch (FileNotFoundException e) {
61: return null;
62: }
63:
64: try {
65: byte[] classBytes = new byte[fi.available()];
66: fi.read(classBytes);
67: return defineClass(name, classBytes, 0, classBytes.length);
68: } catch (IOException e) {
69: return null;
70: } finally {
71: try {
72: fi.close();
73: } catch (java.io.IOException e) {
74: }
75: }
76: }
77:
78: protected java.net.URL findResource(String name) {
79: for (int i = 0; i < dirs.length; i++) {
80: File res = new File(dirs[i], name);
81: if (res.exists())
82: try {
83: return res.toURL();
84: } catch (java.net.MalformedURLException e) {
85: // TODO: probably use the following when we drop JDK 1.3:
86: // throw new RuntimeException(e);
87:
88: return null;
89: }
90: }
91:
92: return null;
93: }
94: }
|