动态编译实例代码
类别: JAVA教程
动态编译实例代码。非常简单。我看也不用注解了吧。
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();}
}
}
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();}
}
}
- 上一篇: Java 面试中的陷阱
- 下一篇: ANT安装、配置
-= 资 源 教 程 =-
文 章 搜 索