import java.io.*;
import java.util.*;
import java.security.*;
public class VersionClassLoader extends SecureClassLoader {
private String version;
public VersionClassLoader(String version) {
this.version = version;
}
public VersionClassLoader(ClassLoader parent, String version) {
super(parent);
this.version = version;
}
protected Class findClass(String initialName)
throws ClassNotFoundException {
String name = getVersionName(initialName);
StringTokenizer st = getClasspath();
while (st.hasMoreTokens()) {
try {
File dir = new File(st.nextToken());
File f = new File(dir,name);
byte[] result = loadClassData(f);
CodeSource codeSource = new CodeSource(dir.toURL(),null);
Class c = defineClass(initialName, result, 0,
(int)f.length(), codeSource);
resolveClass(c);
return c;
} catch (IOException e) {
continue;
}
}
throw new ClassNotFoundException(initialName);
}
private StringTokenizer getClasspath() {
String classpath = System.getProperty("java.class.path");
if (classpath == null) classpath = ".";
return new StringTokenizer(classpath,":");
}
private byte[] loadClassData(File f) throws IOException {
DataInputStream input =
new DataInputStream(new FileInputStream(f));
byte[] content = new byte[(int)f.length()];
input.readFully(content);
return content;
}
private String getVersionName(String initialName) {
int index = initialName.lastIndexOf('.');
if (index == -1)
return version + File.separator + initialName + ".class";
String name = initialName.replace('.',File.separatorChar);
return (name.substring(0,index) + File.separator + version +
File.separator + name.substring(index) + ".class");
}
}