This example uses tools. Jar instead of javac.
/*
? * Creation date: 2004-7-2
? * Created by hongsoft
? * File name: testcompile. Java
? */
Package com. hongsoft. test;
Import java. Io .*;
// Custom Class Loader
Public class mycompile extends classloader
{
? String _ classpath;
? Public static void main (string [] ARGs)
? {
?? New testcompile ();
?}
? Public mycompile ()
? {
?? Super (classloader. getsystemclassloader ());
?? // Compiler type ??
?? _ 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 ()
? {
?? // A3 ???????
?? 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 ("D: //" + classname + ". Class ");
??? Class C = defineclass (BUF, 0, Buf. Length );
??? Try
??? {
???? // Create and return the instance of the class
???? // Return (calculator)
???? 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 =
??? {"-Classpath", _ classpath, "-d", "d: //", javafile. getname ()};
?? // Execute the compilation command
?? Int val = new COM. Sun. Tools. javac. Main (). Compile (CMD );
?? If (Val! = 0)
?? {
??? Throw new runtimeexception ("Compilation error:" + "error code" + val );
??}
?}
? // Read class files in byte array form
? Byte [] readbytes (string filename) throws ioexception
? {
?? // A2
?? File classfile = new file (filename );
?? Byte [] Buf = new byte [(INT) classfile. Length ()];
?? Fileinputstream in = new fileinputstream (classfile );
?? In. Read (BUF );
?? In. Close ();
?? Return Buf;
?}
}