Http://www.java2s.com/Tutorial/Java/0120__Development/CompileString.htm
Import Java. Lang. Reflect. method;
Import Java.net. Uri;
Import Java. util. iterator;
Import Java. util. nosuchelementexception;
Import Javax. Tools. javacompiler;
Import Javax. Tools. javafileobject;
Import Javax. Tools. simplejavafileobject;
Import Javax. Tools. toolprovider;
Public class Compilestring {
Public static Void Main (string [] ARGs) Throws Exception {
Javacompiler compiler = toolprovider. getsystemjavacompiler ();
String program = "class test {" + "public static void main (string [] ARGs ){"
+ "System. Out. println (\" Hello, world \");"
+ "System. Out. println (ARGs. Length);" + "}" + "}";
Iterable <? Extends Javafileobject> fileobjects;
Fileobjects = getjavasourcefromstring (Program );
Compiler. gettask (null, fileobjects). Call ();
Class <?> Clazz = Class . Forname ("test ");
Method M = clazz. getmethod ("Main ", New Class [] {String []. Class });
Object [] _ ARGs = New Object [] { New String [0]};
M. Invoke (null, _ ARGs );
}
Static Iterable <javasourcefromstring> getincluourcefromstring (string code ){
Final Javasourcefromstring jsfs;
Jsfs = New Javasourcefromstring ("code", Code );
Return new Iterable <javasourcefromstring> (){
Public Iterator <javasourcefromstring> iterator (){
Return new Iterator <javasourcefromstring> (){
Boolean Isnext = True ;
Public Boolean Hasnext (){
Return Isnext;
}
Public Javasourcefromstring next (){
If (! Isnext)
Throw new Nosuchelementexception ();
Isnext = False ;
Return Jsfs;
}
Public Void Remove (){
Throw new Unsupportedoperationexception ();
}
};
}
};
}
}
Class Javasourcefromstring Extends Simplejavafileobject {
Final String code;
Javasourcefromstring (string name, string code ){
Super (URI. Create ("String: //" + name. Replace ('.', '/') + kind. Source. Extension), kind. source );
This . Code = code;
}
Public Charsequence getcharcontent ( Boolean Ignoreencodingerrors ){
Return Code;
}
}
Http://www.java2s.com/Tutorial/Java/0120__Development/CompileJavafile.htm
Import Javax. Tools. Diagnostic;
Import Javax. Tools. diagnosticcollector;
Import Javax. Tools. javacompiler;
Import Javax. Tools. javafileobject;
Import Javax. Tools. standardjavafilemanager;
Import Javax. Tools. toolprovider;
Public class Compilefiles2 {
Public static Void Main (string [] ARGs ){
Javacompiler compiler = toolprovider. getsystemjavacompiler ();
Diagnosticcollector <javafileobject> DC;
Dc = New Diagnosticcollector <javafileobject> ();
Standardjavafilemanager sjfm;
Sjfm = compiler. getstandardfilemanager (DC, null, Null );
Iterable <? Extends Javafileobject> fileobjects;
Fileobjects = sjfm. getjavafileobjects (ARGs );
Compiler. gettask (null, sjfm, DC, null, null, fileobjects). Call ();
For (Diagnostic D: DC. getdiagnostics ()){
System. Out. println (D. getmessage ( Null ));
System. Out. printf ("line number = % d \ n", D. getlinenumber ());
System. Out. printf ("file = % s \ n", D. getsource ());
}
}
}