Source code: com/dghda/module/StreamClassLoader.java
1 /* Copyright (C) 2001 Duane Griffin <duanegriffin@users.sourceforge.net>
2 This file is part of Kent.
3
4 Kent is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License as
6 published by the Free Software Foundation; either version 2 of the
7 License, or (at your option) any later version.
8
9 Kent is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 General Public License for more details.
13
14 You should have received a copy of the GNU General Public
15 License along with Kent; see the file COPYING. If not,
16 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 Boston, MA 02111-1307, USA.
18 */
19
20 package com.dghda.module;
21
22 import java.io.*;
23
24 /** A class loader which will attempt to load a classes from a stream. */
25 public class StreamClassLoader extends ClassLoader {
26
27 /** Creates a new stream class loader using the system class loader as its parent. */
28 public StreamClassLoader() {
29 }
30
31 /**
32 Creates a new file class loader using the given class loader as its parent.
33 @param parent The class loader's parent.
34 */
35 public StreamClassLoader (ClassLoader parent) {
36 super (parent);
37 }
38
39 /**
40 Attempts to load a class from the given stream, and instatiate an instance of it.
41 @param name The fully qualified name of the class that should be loaded, or null if it can have any name.
42 @param in The input stream to load the class from.
43 @throws IOException If there was an IO error reading the class data.
44 @throws IllegalAccessException If the class is not accessible.
45 */
46 public Class loadClass (String name, InputStream in) throws IOException, IllegalAccessException {
47
48 // Load the class data from the file
49 byte [] buffer = loadClassData (in);
50
51 // Define the class
52 return defineClass (name, buffer, 0, buffer.length);
53 }
54
55 /** Loads class data from the class file. */
56 protected static byte [] loadClassData (InputStream input) throws IOException {
57
58 // Get the input from the given file
59 BufferedInputStream in = new BufferedInputStream (input);
60
61 // Prepare a buffer to write the output to
62 ByteArrayOutputStream result = new ByteArrayOutputStream();
63 BufferedOutputStream out = new BufferedOutputStream (result);
64
65 // Pipe the input from the file into the output buffer
66 for (int read = in.read(); read != -1; read = in.read())
67 out.write (read);
68
69 // Return the contents of the buffer
70 out.flush();
71 return result.toByteArray();
72 }
73 }