1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.bcel.util;
18
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.util.HashMap;
22 import java.util.Map;
23
24 import org.apache.bcel.classfile.ClassParser;
25 import org.apache.bcel.classfile.JavaClass;
26 import org.apache.bcel.classfile.Utility;
27
28
29
30
31
32
33
34
35 public class ClassLoaderRepository implements Repository {
36
37 private final java.lang.ClassLoader loader;
38 private final Map<String, JavaClass> loadedClasses = new HashMap<>();
39
40 public ClassLoaderRepository(final java.lang.ClassLoader loader) {
41 this.loader = loader;
42 }
43
44
45
46
47 @Override
48 public void clear() {
49 loadedClasses.clear();
50 }
51
52
53
54
55 @Override
56 public JavaClass findClass(final String className) {
57 return loadedClasses.get(className);
58 }
59
60
61
62
63 @Override
64 public ClassPath getClassPath() {
65 return null;
66 }
67
68 @Override
69 public JavaClass loadClass(final Class<?> clazz) throws ClassNotFoundException {
70 return loadClass(clazz.getName());
71 }
72
73
74
75
76 @Override
77 public JavaClass loadClass(final String className) throws ClassNotFoundException {
78 final String classFile = Utility.packageToPath(className);
79 JavaClass RC = findClass(className);
80 if (RC != null) {
81 return RC;
82 }
83 try (InputStream is = loader.getResourceAsStream(classFile + JavaClass.EXTENSION)) {
84 if (is == null) {
85 throw new ClassNotFoundException(className + " not found.");
86 }
87 final ClassParser parser = new ClassParser(is, className);
88 RC = parser.parse();
89 storeClass(RC);
90 return RC;
91 } catch (final IOException e) {
92 throw new ClassNotFoundException(className + " not found: " + e, e);
93 }
94 }
95
96
97
98
99 @Override
100 public void removeClass(final JavaClass clazz) {
101 loadedClasses.remove(clazz.getClassName());
102 }
103
104
105
106
107 @Override
108 public void storeClass(final JavaClass clazz) {
109 loadedClasses.put(clazz.getClassName(), clazz);
110 clazz.setRepository(this);
111 }
112 }