/*
? * Creation date: 2004-7-2
? * Created by hongsoft
? * File name: testcompile. Java
? */
Package com. hongsoft. test;
Import java. Io .*;
// Custom Class Loader
Public class testcompile extends classloader
{
? String _ compiler;
? String _ classpath;
? Public static void main (string [] ARGs)
? {
?? New testcompile ();
?}
? Public testcompile ()
? {
?? Super (classloader. getsystemclassloader ());
?? // Default Compiler
?? If (_ compiler = NULL)
??? _ Compiler = "D: // j2sdk1.4.2 // bin // javac ";
?? _ Classpath = ".";
?? String extraclasspath =
??? "C: // program files // Java // j2re1.4.2 // lib // Rt. Jar ";
?? // = System. getproperty ("Calc. classpath ");
?? If (extraclasspath! = NULL)
?? {
??? _ Classpath =
???? _ Classpath
????? + System. getproperty ("path. separator ")
????? + Extraclasspath;
??}
?? Compile ();
?}
? Public void compile ()
? {?????
?? String filename = "";
?? String classname = "";
?? Try
?? {
??? // Create a temporary file
??? File javafile =
???? File. createtempfile ("compiled _", ". Java", new file ("."));
??? Filename = javafile. getname ();
??? Classname = filename. substring (0, filename. lastindexof ("."));
??? Generatejavafile (javafile, classname );
??? // Compile the file
??? Invokecompiler (javafile );
??? // Create a Java class
??? Byte [] Buf = readbytes (classname + ". Class ");
??? Class C = defineclass (BUF, 0, Buf. Length );
??? Try
??? {
??????? C. newinstance ();
???}
??? Catch (illegalaccessexception E)
??? {
???? Throw new runtimeexception (E. getmessage ());
???}
??? Catch (instantiationexception E)
??? {
???? Throw new runtimeexception (E. getmessage ());
???}
??}
?? Catch (ioexception E)
?? {
??? Throw new runtimeexception (E. getmessage ());
??}
?}
? // Generate a Java File
? Void generatejavafile (File javafile, string classname) throws ioexception
? {
?? Fileoutputstream out = new fileoutputstream (javafile );
?? String text =
??? "Public class"
???? + Classname
???? + "{"
???? + "Public int getcreater () {return 1 ;}"
???? + "}";
?? Out. Write (text. getbytes ());
?? Out. Close ();
?}
? // Compile the Java File
? Void invokecompiler (File javafile) throws ioexception
? {
?? String [] cmd =
??? {_ Compiler, "-classpath", _ classpath, javafile. getname ()};
?? // Execute the compilation command
?? // A1:
?? Process = runtime.getruntime(cmd.exe C (CMD );
?? Try
?? {// Wait until the compiler ends
??? Process. waitfor ();
??}
?? Catch (interruptedexception E)
?? {
??}
?? Int val = process. exitvalue ();
?? If (Val! = 0)
?? {
??? Throw new runtimeexception ("Compilation error:" + "error code" + val );
??}
?}
? // Read class files in byte array form
? Byte [] readbytes (string filename) throws ioexception
? {
??? File classfile = new file (filename );
?? Byte [] Buf = new byte [(INT) classfile. Length ()];
?? Fileinputstream in = new fileinputstream (classfile );
?? In. Read (BUF );
?? In. Close ();
?? Return Buf;
?}
}