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
22 import org.apache.bcel.classfile.ClassParser;
23 import org.apache.bcel.classfile.JavaClass;
24 import org.apache.bcel.classfile.Utility;
25
26
27
28
29
30
31
32
33
34
35
36 abstract class AbstractClassPathRepository implements Repository {
37
38 private final ClassPath classPath;
39
40 AbstractClassPathRepository(final ClassPath classPath) {
41 this.classPath = classPath;
42 }
43
44 @Override
45 public abstract void clear();
46
47 @Override
48 public abstract JavaClass findClass(final String className);
49
50 @Override
51 public ClassPath getClassPath() {
52 return classPath;
53 }
54
55
56
57
58
59
60
61
62
63
64
65 @Override
66 public JavaClass loadClass(final Class<?> clazz) throws ClassNotFoundException {
67 final String className = clazz.getName();
68 final JavaClass repositoryClass = findClass(className);
69 if (repositoryClass != null) {
70 return repositoryClass;
71 }
72 String name = className;
73 final int i = name.lastIndexOf('.');
74 if (i > 0) {
75 name = name.substring(i + 1);
76 }
77
78 try (InputStream clsStream = clazz.getResourceAsStream(name + JavaClass.EXTENSION)) {
79 return loadClass(clsStream, className);
80 } catch (final IOException e) {
81 return null;
82 }
83 }
84
85 private JavaClass loadClass(final InputStream inputStream, final String className) throws ClassNotFoundException {
86 try {
87 if (inputStream != null) {
88 final ClassParser parser = new ClassParser(inputStream, className);
89 final JavaClass clazz = parser.parse();
90 storeClass(clazz);
91 return clazz;
92 }
93 } catch (final IOException e) {
94 throw new ClassNotFoundException("Exception while looking for class " + className + ": " + e, e);
95 }
96 throw new ClassNotFoundException("ClassRepository could not load " + className);
97 }
98
99
100
101
102
103
104
105
106
107 @Override
108 public JavaClass loadClass(String className) throws ClassNotFoundException {
109 if (className == null || className.isEmpty()) {
110 throw new IllegalArgumentException("Invalid class name " + className);
111 }
112 className = Utility.pathToPackage(className);
113 final JavaClass clazz = findClass(className);
114 if (clazz != null) {
115 return clazz;
116 }
117 try (InputStream inputStream = classPath.getInputStream(className)) {
118 return loadClass(inputStream, className);
119 } catch (final IOException e) {
120 throw new ClassNotFoundException("Exception while looking for class " + className + ": " + e, e);
121 }
122 }
123
124 @Override
125 public abstract void removeClass(final JavaClass javaClass);
126
127 @Override
128 public abstract void storeClass(final JavaClass javaClass);
129 }