/////// NetClassLoader.java ///////
import java.net.*;
import java.io.*;
import java.util.Hashtable;
import java.lang.reflect.Method;
/** A class loader to Load name.class from a given url.
* @author Paul S. Wang
*/
public class NetClassLoader extends ClassLoader
{/** Reads name.class at URL int byte array.
* @param name name.class is file to load
* @return array contain bytecodes of class
*/
private byte[] loadFromUrl(String name)
throws ClassNotFoundException
{ try
{ URL urlobj = new URL(urlstr+name+".class");
BufferedInputStream in =
new BufferedInputStream(urlobj.openStream());
int len = in.available();
if ( len <= 0 )
throw new ClassNotFoundException("Empty Class");
byte[] buf = new byte[len];
in.read(buf);
in.close();
return buf;
} catch (IOException e)
{ throw new ClassNotFoundException(e.toString());
}
}
/** Coonstructor.
* @param cb the URL string where loader will find classes.
*/
public NetClassLoader(String cb) // constructor
{ urlstr = cb; }
protected NetClassLoader() {}
/** Overrides loadClass from ClassLoader.
* @param name name.class is file to load
* @param resolve whether to resolve loaded class
* @return Class object created
*/
public synchronized Class
loadClass(String name, boolean resolve)
throws ClassNotFoundException
{ Class cbj;
try
{ cbj = (Class) checkList.get(name);
if (cbj == null)
{ cbj = findSystemClass(name);
if ( cbj != null ) return cbj;
}
} catch (ClassNotFoundException e) { }
byte[] data = loadFromUrl(name);
cbj = defineClass(null, data, 0, data.length);
checkList.put(name, cbj);
if (resolve) resolveClass(cbj);
return cbj;
}
/** main runs any remote application.
* java NetClassLoader "http://SymbolicNet.mcs.kent.edu/" Factorial 6
* gets the display:
* class loaded: Factorial
* 720
*/
public static void main(String[] args)
{ if ( args.length < 2 )
{ System.err.println(
"Usage: Java NetClassLoader url ClassName arg1 ...");
System.exit(1);
}
try
{ NetClassLoader loader = new NetClassLoader(args[0]);
Class cbj = loader.loadClass(args[1], true);
System.out.println("class loaded: " + cbj.getName());
Class[] param = new Class[1];
param[0] = args.getClass();
Method m = cbj.getMethod("main", param);
int n = args.length-2;
String[] arg = new String[n];
if ( n > 0 ) System.arraycopy(args, 2, arg, 0, n);
Object[] argArray = new Object[1];
argArray[0] = arg;
m.invoke(null, argArray);
} catch (Exception e)
{ System.err.print(e.getMessage()); System.exit(1); }
}
private String urlstr;
private Hashtable checkList = new Hashtable();
}