This case is not directly using Javac, but use Tools.jar
/ *? * Create a date 2004-7-2? * Create a human hongsoft? * File name testcompile.java?*/package com.hongsoft.test;
Import java.io. *;
// Customized class equipment 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 ("cagc.classpath"); ?? IF (extraclasspath! = Null) ?? {??? _ classpath = ???? _ classpath ????? system.getproperty ("path.separator") ????? extraclasspath; ??} ?? compile ();?}
PUBLIC VOID Compile ()? {?? // A3 ???????? String filename = ""; ?? String classname = ""; ?? Try ?? {??? // created a temporary file ??? file javafile = ???? file.createTempfile ("Compiled_", ".java", new file (".")); ??? filename = javafile.getname (); ??? ClassName = filename. Substring (0, filename.lastIndexof (".")); ??? generatejavafile (javafile, classname); ??? // Compile file ??? InvokeCompiler (javafile); ??? // Create a Java class??? Byte [] buf = readbytes ("d: //" ClassName ".class"); ??? Class C = DefineClass (buf, 0, buf.length); ??? Try ??? {??? ? // Create and return instances of the class ???? // Return (Calculator) ???? c.newinstance (); ???} ??? catch (IllegalaccessExcection E) ??? {???? throw New runtimeException (E.GetMessage ()); ???} ??? Catch (instantiationException e) ??? {???? throw new runtimeException (E.GetMessage ()); ???} ??} ?? Catch (IOException E) ?? {??? throw new runtimeException (E.GETMESSAGE ()); ??}?}
? // generated 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 ()); ?? OUT. CLOSE ();?}? // Compile java file? Void invokecompiler (file javafile) throws ooException? {?? string [] cmd = ??? {"-classpath", _classpath, "-d", "D: / / ", javafile.getname ()}; ?? // Execute the compile command ?? int val = new com.sun.tools.javac.main (). Compile (cmd);
?? IF (Val! = 0) ?? {??? throw new runtimeException ("Compiling error:" "error code" val); ??}?
? // read the file in the byte array? Byte [] readbytes (String filename) throws ooException? {?? // 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 ;?}
}