/ * * Create a date 2004-7-2 * Create a hongsoft * file name TestCompile.java * / package com.hongsoft.test;
Import java.io. *;
// Customized 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 files invokeCompiler (javafile); // create a java class byte [] BUF = ReadBytes (classname ".class"); class c = defineclass (buf, 0, buf.length); try {c.newinstance ();} catch (illegalaccessExcection e) {throw new runtimeException (E.getMessage () );} Catch (instantiationException e) {throw new runtimeException (E.GetMessage ());}} catch (ieException e) {throw new runtimeException (E.getMessage ());}}
// java files generated 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 oews oewception {string [] cmd = {_compiler," -classpath ", _CLASSPATH, JAVAFILE.GETNAME ()}; // Execute Compile Command // A1: Process Process = runtime.Getruntime (); exec (cmd); try {// Waiting for the compiler to end Process.waitfor ();} catch (InterruptedException E) {} int val = process.exitvalue (); if (val! = 0) {throw new runtimeException ("Compiling error:" "error code" val);}}
// read the file in the byte array byte [] readbytes (String filename) throw 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;}
}