1 package ca.spaz.util;
2
3 import java.io.*;
4 import java.util.zip.*;
5
6 import javax.swing.ImageIcon;
7
8 /***
9 * A special class for loading classes from an jar file.
10 *
11 * @author Aaron Davidson
12 */
13 public final class Loader extends ClassLoader {
14 private ZipFile archive;
15
16 public Loader(File file) {
17 try {
18 archive = new ZipFile(file);
19 } catch (Exception e) {
20 e.printStackTrace();
21 }
22 }
23
24 /***
25 * Create a new instance of a class in this jar file.
26 * Must have a basic constructor with no arguments.
27 *
28 * @param name the class name to instantiate
29 *
30 * @return an Object created from the given class
31 */
32 public Object newInstance(String name) {
33 try {
34 Class c = this.loadClass(name, true);
35 return c.newInstance();
36 } catch (Exception e) {
37 e.printStackTrace();
38 }
39 return null;
40 }
41
42 /***
43 * Load a class by name.
44 * @see java.lang.ClassLoader#loadClass()
45 */
46 protected Class loadClass(String name, boolean resolve)
47 throws ClassNotFoundException {
48 Class c = findLoadedClass(name);
49 if (c == null) {
50 try {
51 c = findSystemClass(name);
52 } catch (Exception e) {}
53 }
54 if (c == null) {
55 try {
56 byte data[] = loadClassData(name);
57 if (data != null) {
58 c = defineClass(name, data, 0, data.length);
59 }
60 if (c == null) {
61 throw new ClassNotFoundException(name);
62 }
63 } catch (IOException e) {
64 throw new ClassNotFoundException("Error reading class: " + name);
65 }
66 }
67 if (resolve) {
68 resolveClass(c);
69 }
70 return c;
71 }
72
73 private byte[] loadClassData(String filename) throws IOException {
74 if (archive == null) return null;
75 filename = filename.replaceAll("//.", "/");
76 return loadResource(filename + ".class");
77 }
78
79 private byte[] loadResource(String name) {
80 try {
81 ZipEntry ze = archive.getEntry(name);
82 if (ze == null) {
83 return null;
84 }
85 InputStream in = archive.getInputStream(ze);
86 int size = (int)ze.getSize();
87 byte buff[] = new byte[size];
88 BufferedInputStream bis = new BufferedInputStream(in);
89 DataInputStream dis = new DataInputStream(bis);
90
91 int n = 0;
92 try {
93 while (true) {
94 buff[n++] = (byte)dis.readByte();
95 }
96 } catch (EOFException eof) {}
97 n--;
98 dis.close();
99 return buff;
100 } catch (Exception e) {
101 e.printStackTrace();
102 }
103 return null;
104 }
105
106 public ImageIcon loadImageIcon(String name) {
107 byte buff[] = loadResource(name);
108 if (buff != null) {
109 return new ImageIcon(buff);
110 } else {
111 return null;
112 }
113 }
114
115 }