package dcj.util;
import java.lang.*;
import java.net.*;
import java.io.*;
import java.util.Hashtable;
/**
* Source code from "Java Distributed Computing", by Jim Farley.
*
* Class: URLClassLoader
* Example: 2-10
* Description: A class loader that uses loads classes referenced via URLs.
* This type of class loader is used internally by Java-enabled Web
* browsers to load classes for applets.
*/
public class URLClassLoader extends StreamClassLoader {
URL classURL = null;
InputStream classStream = null;
protected String parseClassName(String classLoc)
throws ClassNotFoundException {
String className = null;
// Try constructing a URL around the class locator
try { classURL = new URL(classLoc); }
catch (MalformedURLException e) {
throw new ClassNotFoundException("Bad URL \"" + classLoc +
"\" given: " + e);
}
System.out.println("File = " + classURL.getFile());
System.out.println("Host = " + classURL.getHost());
// Get the file name from the URL
String filename = classURL.getFile();
// Make sure we're referencing a class file, then parse the class name
if (! filename.endsWith(".class"))
throw new ClassNotFoundException("Non-class URL given.");
else
className = filename.substring(0, filename.lastIndexOf(".class"));
System.out.println("Classname = " + className);
return className;
}
protected void initStream(String classLoc) throws IOException {
// Ask the URL to open a stream to the class object
classStream = classURL.openStream();
}
protected Class readClass(String classLoc, String className)
throws IOException, ClassNotFoundException {
// See how large the class file is...
URLConnection conn = classURL.openConnection();
int classSize = conn.getContentLength();
System.out.println("Class file is " + classSize + " bytes.");
// Read the class bytecodes from the stream
DataInputStream dataIn = new DataInputStream(classStream);
int avail = dataIn.available();
System.out.println("Available = " + avail);
System.out.println("URLClassLoader: Reading class from stream...");
byte[] classData = new byte[classSize];
dataIn.readFully(classData);
// Parse the class definition from the bytecodes
Class c = null;
System.out.println("URLClassLoader: Defining class...");
try { c = defineClass(classData, 0, classData.length); }
catch (ClassFormatError e) {
throw new ClassNotFoundException("Format error found in class data.");
}
return c;
}
} |