2015年7月6日星期一

自动化编译Java代码样例

前置条件:
Java 6及以上
设置JAVA_HOME
tools.jar位置正确
说明:如果 ToolProvider.getSystemJavaCompiler() 不能创建 JavaCompiler
如果 tools.jar 不在应用程序类路径中,ToolProvider.getSystemJavaCompiler() 方法可以返回 null。CharStringCompiler 类检测到这一配置问题后将抛出一个异常,并给出修复建议。注意,Sun 许可证允许跟随 JRE 一起重新分发 tools.jar。相关类说明:

ToolProvider:Provides methods for locating tool providers, for example, providers of compilers.

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;

import javax.tools.JavaCompiler;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import javax.tools.JavaCompiler.CompilationTask;

/**
 * @author YuFa
 *
 */
public class CompilerTest { 
      
    public static void main(String[] args) throws Exception {       
       String source = "public class Main {" +
                               "public static void main(String[] args) {" +
                                   "System.out.println(\"Hello World!\");" +
                                "} " +
                           "}";       
       
       
       JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
       StandardJavaFileManager fileManager =  compiler.getStandardFileManager(null, null, null); 
       StringSourceJavaObject sourceObject = new CompilerTest.StringSourceJavaObject("Main", source); 
       List<StringSourceJavaObject> fileObjects =  Arrays.asList(sourceObject); 
       CompilationTask task = compiler.getTask(null, fileManager, null, null, null, fileObjects); 
       
       boolean result = task.call(); 
       if (result) { 
          System.out.println("Compile succeeded!"); 
       }  else {
          System.out.println("Compile failed!"); 
       }
    } 
  
    static class StringSourceJavaObject extends SimpleJavaFileObject { 
  
       private String content = null; 
       public StringSourceJavaObject(String name, String content) throws URISyntaxException { 
          super(URI.create("string:///" + name.replace('.','/') +  Kind.SOURCE.extension), Kind.SOURCE); 
          this.content = content; 
       } 
  
       @Override
       public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { 
          return content; 
       } 
    } 
 }

没有评论:

发表评论