1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45 package org.xnap.util;
46
47 import java.io.DataInputStream;
48 import java.io.IOException;
49 import java.util.zip.ZipEntry;
50 import java.util.zip.ZipFile;
51
52 /***
53 * Provides a class loader that can load classes from zip files. BTW, jar
54 * files are in zip format.
55 */
56 public class ZipFileClassLoader extends ClassLoader
57 {
58
59 private ZipFile zipFile;
60
61 public ZipFileClassLoader(ZipFile zipFile)
62 {
63 this.zipFile = zipFile;
64 }
65
66 public String getFilename()
67 {
68 return zipFile.getName();
69 }
70
71 protected Class loadClass(String name, boolean resolve)
72 throws ClassNotFoundException
73 {
74 Class c = findLoadedClass(name);
75 if (c == null)
76 {
77 try {
78 c = findSystemClass(name);
79 }
80 catch(Exception e) {
81 }
82 }
83
84 if (c == null) {
85 String filename = name.replace('.', '/') + ".class";
86
87 try {
88 ZipEntry entry = zipFile.getEntry(filename);
89
90 if (entry == null) {
91 throw new ClassNotFoundException(name);
92 }
93 byte data[] = loadClassData(entry);
94
95 c = defineClass(name, data, 0, data.length);
96 if (c == null) {
97 throw new ClassNotFoundException(name);
98 }
99 }
100 catch(IOException e) {
101 throw new ClassNotFoundException("Error reading file: " +
102 filename);
103 }
104 }
105
106 if (resolve) {
107 resolveClass(c);
108 }
109
110 return c;
111 }
112
113 private byte[] loadClassData(ZipEntry entry) throws IOException
114 {
115 DataInputStream in
116 = new DataInputStream(zipFile.getInputStream(entry));
117 byte[] data = new byte[(int)entry.getSize()];
118
119 in.readFully(data);
120 in.close();
121
122 return data;
123 }
124
125 }