import java.net.*;
import java.io.*;
import java.lang.reflect.*;
/**
* class to test class reloading
*/
public class CLTest{
public static void main(String[] args) {
String cs = "public class Foo { public static int getNum(){ int tmp = 666;System.out.println(\"value is \"+tmp);return tmp;}}";
int i = 100;
Runtime r = Runtime.getRuntime();
try {
// loop until we press enter
while (System.in.available() == 0) {
modifyClass(cs,i);
int ires = execClass();
System.out.println("ires="+ires);
i+=100;
r.gc();
System.out.println(" free mem: "+ r.freeMemory() + " of " + r.totalMemory());
}
} catch (Exception e){
System.out.println(e);
System.exit(0);
}
}
// replace the 666 in the code argument with the number i
// write it as file Foo.Java and compile it
public static void modifyClass(String code, int i) {
Runtime r = Runtime.getRuntime();
BufferedWriter writer;
File foo=new File("E:\\tmp\\Foo.java");
foo.delete();
String newcode = code.replaceFirst("666",""+i);
try {
writer = new BufferedWriter(new FileWriter(foo,false));
writer.write(newcode,0,newcode.length());
writer.close();
//System.out.println("Written ..."+newcode);
Process p =r.exec("javac E:\\tmp\\Foo.java");
p.waitFor();
System.out.println("compile complete");
} catch (Exception e) {
System.out.println(e);
System.exit(0);
}
}
// get a new class loader, load the class and run the getNum method
public static int execClass() {
Object res=null;
try {
URLClassLoader cl;
URL[] urls = {new File("E:\\tmp/").toURL()};
cl = new URLClassLoader(urls);
Class c = cl.loadClass("Foo");
Method m = c.getMethod("getNum",null);
res = m.invoke (null,null);c=null;
} catch (Exception e) {
System.out.println(e);
System.exit(0);
}
return ((Integer)res).intValue();
}
}