For Java sdk1.6 Implementation of Java Dynamic compiling classes:
Import java. Io. ioexception;
Import java. Lang. Reflect. method;
Import java.net. Uri;
Import java. util. arrays;
Import javax. Tools. javacompiler;
Import javax. Tools. javafileobject;
Import javax. Tools. simplejavafileobject;
Import javax. Tools. standardjavafilemanager;
Import javax. Tools. toolprovider;
Public class compilestring {
Public static void main (string [] ARGs) throws exception {
// Obtain the dynamic compiler through the system tool provider
Javacompiler compiler = toolprovider. getsystemjavacompiler ();
// Obtain a file manager. Its function is to provide rules for all file operations,
// For example, the source code path, the compiled classpath, and the target directory of the class file. The default values are provided for relevant attributes.
Standardjavafilemanager filemanager = compiler. getstandardfilemanager (null, null, null );
Stringobject so = new stringobject ("demo. calculatortest", "package demo;" +
"Class calculatortest {" +
"Public int multiply (INT multiplicand, int multiplier) {" +
"System. Out. println (multiplicand);" +
"System. Out. println (multiplier);" +
"Return multiplicand * multiplier;" +
"}" +
"}");
Javafileobject file = so;
// Specify the command line parameters of javac
//Note: It is best to place the compiled. Class file to the class path of the current JVM instance. Otherwise, the file will not be loaded.
// Iterable Options = arrays. aslist ("-D", "E: \ workspace \ hellosbt \ target \ scala-2.9.1 \ Classes ");
Iterable Options = arrays. aslist ("-D", "E: \ workplace \ javacompiletest \ bin ");
// Specify which source files need to be compiled
Iterable <? Extends javafileobject> files = arrays. aslist (File );
// Return the compilation object
Javacompiler. compilationtask task = compiler. gettask (null, filemanager, null, options, null, files );
// Execute this compilation task
Boolean result = task. Call ();
If (result ){
System. Out. println ("compiled successfully ");
// Return the reference corresponding to the class name
Class <?> Clazz = Class. forname ("calculatortest ");
//ClassA new instance of the class represented by the object
Object instance = clazz. newinstance ();
// ReturnsMethodObject, which reflectsClassThe specified public member method of the class or interface represented by the object.
Method M = clazz. getmethod ("Multiply", new class [] {Int. Class, Int. Class });
// Input corresponding parameters
Object [] O = new object [] {1, 2 };
M. Invoke (instance, O );
}
}
}
Class stringobject extends simplejavafileobject {
Private string contents = NULL;
Public stringobject (string classname, string contents) throws exception {
// Kind. source indicates the source file written in Java programming language
Super (New uri (classname), kind. source );
This. Contents = contents;
}
Public charsequence getcharcontent (Boolean ignoreencodingerrors) throws ioexception {
Return contents;
}
}