The Tool.jar under the JDK / LIB directory contains a complete Java compiler package that uses it to realize the runtime of the class file and compile load. Below is an example:
Import java.io. *;
Import java.util. *;
Import java.lang.reflect. *;
Public class maketodayclass {
Date Today = new date ();
String TodayMillis = long.tostring (Today.gettime ());
String TodayClass = "z_" TodayMillis;
String TodaySource = TodayClass ".java";
Public static void main (string args []) {
MaketodayClass MTC = New MaketodayClass ();
Mtc.createit ();
IF (Mtc.Compileit ()) {
System.out.println ("Running" MTC.TodayClass ": / n / n");
Mtc.runit ();
}
Else
System.out.println (Mtc.todaySource "IS BAD.");
}
Public void create () {
Try {
FileWriter AWriter = New FileWriter (TodaySource, TRUE);
AWRITER.WRITE ("Public Class" TodayClass "{");
AWRITER.WRITE ("Public Void Doit () {");
AWRITER.WRITE ("System.out.Println (/" TodayMillis ");")
AWriter.write ("}} / n");
Awriter.flush ();
awriter.close ();
}
Catch (Exception E) {
E.PrintStackTrace ();
}
}
Public boolean compileit () {
String [] Source = {new string (todaySource)};
BYTEARRAYOUTPUTSTREAM baos = new byteArrayoutputStream ();
New sun.tools.javac.main (baos, source [0]). Compile (SOURCE);
// if using jdk> = 1.3 THEN USE
// public static int com.sun.tools.javac.main.Compile (Source);
Return (Baos.Tostring (). Indexof ("Error") == - 1);
}
Public void runit () {
Try {
Class params [] = {};
Object paramsobj [] = {};
Class thisclass = class.Forname (TodayClass);
Object iClass = thisclass.newinstance ();
Method thismethod = thisclass.getDeclaredMethod ("DOIT", Params); thismethod.invoke (iClass, paramsobj);
}
Catch (Exception E) {
E.PrintStackTrace ();
}
}
}