package MyPackage;
import java.io.*;
public class RecursiveClassLoader extends ClassLoader {
String defdir;
public RecursiveClassLoader(String defdir) {
this.defdir = defdir;
if (this.defdir == null)
this.defdir = System.getProperty("user.dir", "");
}
/**
* loadClass Recursively searches for a class by the name of name,
* starting from dir.
*
* @param dir Starting search directory
* @param name Class name (without .class)
* @return The resulting Class object
* @throws ClassNotFoundException If the class is not found
*/
public Class> loadClass(String dir, String name) throws ClassNotFoundException {
int idx = name.lastIndexOf('.');
String qualified = name;
if (idx > 0) {
name = name.substring(idx + 1);
}
try {
File file = search(dir, name + ".class");
if (file != null) {
FileInputStream in = new FileInputStream(file);
byte[] buffer = new byte[in.available()];
in.read(buffer);
Class c = defineClass(qualified, buffer, 0, buffer.length);
return c;
}
} catch (Throwable t) {
}
return super.loadClass(qualified);
}
/**
* loadClass Recursively searches for a class by the name of name,
* starting from the default directory.
* @param name Class name (without .class)
* @return The resulting Class object
* @throws ClassNotFoundException If the class is not found
*/
public Class> loadClass(String name) throws ClassNotFoundException {
return loadClass(defdir, name);
}
private File search(String dir, String name) {
File[] list = new File(dir).listFiles();
for (File f : list) {
if (f.isDirectory()) {
File ret = search(f.getPath(), name);
if (ret != null)
return ret;
}
if (f.getName().equalsIgnoreCase(name)) {
return f;
}
}
return null;
}
}