01: package dalma.test;
02:
03: import org.apache.commons.io.IOUtils;
04: import org.apache.commons.javaflow.bytecode.transformation.ResourceTransformer;
05: import org.apache.commons.javaflow.bytecode.transformation.bcel.BcelClassTransformer;
06:
07: import java.io.IOException;
08: import java.io.InputStream;
09:
10: public final class TestClassLoader extends ClassLoader {
11: private ResourceTransformer transformer = new BcelClassTransformer();
12:
13: public TestClassLoader(ClassLoader parent) {
14: super (parent);
15: }
16:
17: private boolean shouldBeRewritten(String s) {
18: return s.startsWith("test.");
19: }
20:
21: protected synchronized Class loadClass(String name, boolean resolve)
22: throws ClassNotFoundException {
23:
24: Class c = findLoadedClass(name);
25:
26: if (c == null && shouldBeRewritten(name)) {
27: InputStream is = super .getResourceAsStream(name.replace(
28: '.', '/')
29: + ".class");
30: if (is != null) {
31: try {
32: byte[] buf = IOUtils.toByteArray(is);
33: buf = transformer.transform(buf);
34: c = defineClass(name, buf, 0, buf.length);
35: } catch (IOException e) {
36: throw new ClassNotFoundException(
37: "failed to read the class file", e);
38: }
39: }
40: }
41:
42: if (c == null) {
43: // delegate
44: final ClassLoader parent = getParent();
45: if (parent != null)
46: c = parent.loadClass(name);
47: else
48: throw new ClassNotFoundException(name);
49: }
50:
51: if (resolve)
52: resolveClass(c);
53: return c;
54: }
55: }
|