Packagecom.bjsxt.test;ImportJava.io.BufferedReader;ImportJava.io.BufferedWriter;ImportJava.io.File;ImportJava.io.FileWriter;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.Writer;ImportJavax.tools.JavaCompiler;ImportJavax.tools.ToolProvider; Public classTest { Public Static voidMain (string[] args)throwsIOException {//through the IO stream operation, the string is stored as a temporary file (Hi.java), and then the dynamic compilation method is called! String str = "public class Hi {public static void main (string[] args) {System.out.println (\" haha,sxt!\ ");}"; File File=NewFile ("D://hi.java"); WriteFile (FILE,STR); Javacompiler compiler=Toolprovider.getsystemjavacompiler (); intresult = Compiler.run (NULL,NULL,NULL, "D://hi.java"); System.out.println (Result==0? " Compilation succeeded ":" Compilation Failed "); //calling execution class through runtimeRuntime Run =Runtime.getruntime (); Process Process= Run.exec ("Java-cp d://Hi"); InputStream in=Process.getinputstream (); BufferedReader Reader=NewBufferedReader (NewInputStreamReader (in)); String Info= ""; while((Info=reader.readline ())! =NULL) {System.out.println (info); } /*try {url[] urls = new url[] {new URL ("file:/" + "c:/myjava/")}; URLClassLoader loader = new URLClassLoader (URLs); Class C = Loader.loadclass ("HelloWorld"); The main method of calling the Load class is M = C.getmethod ("main", String[].class); M.invoke (null, (Object) New string[]{}); Since the variable parameter is JDK5.0. M.invoke (null, (Object) New string[]{}), which compiles to: M.invoke (null, "AA", "BB"), there is a mismatch between the parameter numbers. Therefore, it is necessary to add (Object) transformation to avoid this problem. public static void Main (string[] args)} catch (Exception e) {e.printstacktrace (); } */ } Private Static voidWriteFile (File file,string str)throwsIOException {//1. Defining character output stream objectsWriter fw=NewFileWriter (file); BufferedWriter BW=NewBufferedWriter (FW); //2. Write by linebw.write (str); Bw.newline (); Bw.write ("//I Love You"); Bw.flush (); //3. Close the streamFw.close (); System.out.println ("Write succeeded"); } }Denamiccompile
Dynamically compiling Java code and executing