动态编译实例代码。非常简单。

类别:Java 点击:0 评论:0 推荐:
动态编译实例代码。非常简单。我看也不用注解了吧。 import java.io.*;
import java.util.*;
import java.lang.reflect.*;
import java.io.File;   public class CompileTest{
 static com.sun.tools.javac.Main javac = new com.sun.tools.javac.Main();
 public static void main(String[] args){
  try{
   File file = File.createTempFile("RunTime",".java",new File(System.getProperty("user.dir"))); 
   String filename = file.getName();
   String classname = filename.substring(0,filename.indexOf('.'));
   PrintWriter out = new PrintWriter(new FileOutputStream(file));
   out.println("public class "+classname+"{");
   out.println("public static void main(String[] args){");
   out.println("System.out.println(\"Yes!\");");
   out.println("}}");
   out.flush();
   out.close();  
   String[] arg = new String[]{"-d",System.getProperty("user.dir"),filename};
   int status = javac.compile(arg); 
   Class cls = Class.forName(classname);
   Method main = cls.getMethod("main", new Class[]{String[].class} );
   main.invoke(null, new Object[] { new String[0] });
   file.delete(); 
   file = new File(classname+".class");
   file.delete();
  }catch(Exception e){e.printStackTrace();} 
  
 } 
}

本文地址:http://com.8s8s.com/it/it15336.htm