Java 动态编译组件 & 类动态加载

1、JDK6 动态编译组件

  Java SE 6 之后自身集成了运行时编译的组件:javax.tools,存放在 tools.jar 包里,可以实现 Java 源代码编译,帮助扩展静态应用程序。该包中提供主要类可以从 Java String、StringBuffer 或其他 CharSequence 中获取源代码并进行编译。接下来通过代码一步步讲述如何利用 JDK6 特性进行运行时编译。

复制代码
 // 通过 ToolProvider 取得 JavaCompiler 对象,JavaCompiler 对象是动态编译工具的主要对象
 JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); 

 // 通过 JavaCompiler 取得标准 StandardJavaFileManager 对象,StandardJavaFileManager 对象主要负责
 // 编译文件对象的创建,编译的参数等等,我们只对它做些基本设置比如编译 CLASSPATH 等。
 StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); 

 // 因为是从内存中读取 Java 源文件,所以需要创建我们的自己的 JavaFileObject,即 InMemoryJavaFileObject 
 JavaFileObject fileObject = new InMemoryJavaFileObject(className, codeString); 
 Iterable<? extends JavaFileObject> files = Arrays.asList(fileObject); 

  // 从文件读取编译源代码
  //Files[] javafiles = ... ; // input for first compilation task
  //Iterable<? extends JavaFileObject> files = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(javafiles));

 // 编译结果信息的记录
 StringWriter sw = new StringWriter(); 

 // 编译目的地设置
 Iterable options = Arrays.asList("-d", classOutputFolder); 

 // 通过 JavaCompiler 对象取得编译 Task 
 JavaCompiler.CompilationTask task = 
 compiler.getTask(sw, fileManager, null, options, null, files); 

 // 调用 call 命令执行编译,如果不成功输出错误信息
 if (!task.call()) { 
 String failedMsg = sw.toString(); 
 System.out.println(“Build Error:” + failedMsg); 
 } 

 // 自定义 JavaFileObject 实现了 SimpleJavaFileObject,指定 string 为 java 源代码,这样就不用将源代码
 // 存在内存中,直接从变量中读入即可。
 public static class InMemoryJavaFileObject extends SimpleJavaFileObject { 
   private String contents = null; 

   public InMemoryJavaFileObject(String className, String contents) { 
     super(URI.create("string:///" + className.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE); 
     this.contents = contents; 
   } 

   public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { 
     return contents; 
   } 
 } 
复制代码

http://www.ibm.com/developerworks/cn/java/j-lo-jdk6forosgi/

http://www.ibm.com/developerworks/cn/java/j-lo-jse64/index.html?S_TACT=105AGX52&S_CMP=techcto

http://docs.oracle.com/javase/6/docs/api/javax/tools/JavaCompiler.html

http://dlc.sun.com.edgesuite.net/jdk/jdk-api-localizations/jdk-api-zh-cn/publish/1.6.0/html/zh_CN/api/javax/tools/JavaCompiler.html

猜你喜欢

转载自zh-ka-163-com.iteye.com/blog/2230745