1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.jci.stores;
18
19 import org.apache.commons.jci.utils.ConversionUtils;
20 import org.apache.commons.logging.Log;
21 import org.apache.commons.logging.LogFactory;
22
23
24
25
26
27
28
29 public final class ResourceStoreClassLoader extends ClassLoader {
30
31 private final Log log = LogFactory.getLog(ResourceStoreClassLoader.class);
32
33 private final ResourceStore[] stores;
34
35 public ResourceStoreClassLoader( final ClassLoader pParent, final ResourceStore[] pStores ) {
36 super(pParent);
37
38 stores = new ResourceStore[pStores.length];
39 System.arraycopy(pStores, 0, stores, 0, stores.length);
40 }
41
42 private Class<?> fastFindClass(final String name) {
43
44 if (stores != null) {
45 for (ResourceStore store : stores) {
46 final byte[] clazzBytes = store.read(ConversionUtils.convertClassToResourcePath(name));
47 if (clazzBytes != null) {
48 log.debug(getId() + " found class: " + name + " (" + clazzBytes.length + " bytes)");
49 return defineClass(name, clazzBytes, 0, clazzBytes.length);
50 }
51 }
52 }
53
54 return null;
55 }
56
57 @Override
58 protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
59
60 Class<?> clazz = findLoadedClass(name);
61
62 if (clazz == null) {
63 clazz = fastFindClass(name);
64
65 if (clazz == null) {
66
67 final ClassLoader parent = getParent();
68 if (parent != null) {
69 clazz = parent.loadClass(name);
70
71 } else {
72 throw new ClassNotFoundException(name);
73 }
74
75 } else {
76 log.debug(getId() + " loaded from store: " + name);
77 }
78 }
79
80 if (resolve) {
81 resolveClass(clazz);
82 }
83
84 return clazz;
85 }
86
87 @Override
88 protected Class<?> findClass( final String name ) throws ClassNotFoundException {
89 final Class<?> clazz = fastFindClass(name);
90 if (clazz == null) {
91 throw new ClassNotFoundException(name);
92 }
93 return clazz;
94 }
95
96 private String getId() {
97 return "" + this + "[" + this.getClass().getClassLoader() + "]";
98 }
99 }