public class CompilerAPITester { private static String JAVA_SOURCE_FILE = "DynamicObject.java"; private static String JAVA_CLASS_FILE = "DynamicObject.class"; private static String JAVA_CLASS_NAME = "DynamicObject"; public static void main(String[] args) { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); generateJavaClass(); try { //将产生的类文件拷贝到程序的ClassPath下面,下面这一行代码是特定于Windows+IntelliJ IDEA 6.0项目,不具有移植性 Runtime.getRuntime().exec("cmd /c copy "+JAVA_CLASS_FILE+" classes\\production\\JDK6Features"); Iterable<? extends JavaFileObject> sourcefiles = fileManager.getJavaFileObjects(JAVA_SOURCE_FILE); compiler.getTask(null, fileManager, null, null, null, sourcefiles).call(); fileManager.close(); Class.forName(JAVA_CLASS_NAME).newInstance();//创建动态编译得到的DynamicObject类的实例 } catch (Exception ex) { ex.printStackTrace(); } } public static void generateJavaClass(){ try { FileWriter fw = new FileWriter(JAVA_SOURCE_FILE); BufferedWriter bw = new BufferedWriter(fw); bw.write("public class "+JAVA_CLASS_NAME+"{"); bw.newLine(); bw.write("public "+JAVA_CLASS_NAME+"(){System.out.println(\"In the constructor of DynamicObject\");}}"); bw.flush(); bw.close(); } catch (IOException ex) { ex.printStackTrace(); } } } |
·Java初学者专区 | ·Java高级技术 | ||
·Java图像与多媒体 | ·Java网络编程 | ||
·Eclipse | ·Hibernate | ||
·Spring | ·Struts | ||
·Java设计模式 | ·EJB开发 |