JavaCompiler --JDK6 API的简介


在非常多Java应用中需要在程式中调用Java编译器来编译和运行。但在早期的版本中(Java SE5及以前版本)中只能通过tools.jar中的com.sun.tools.javac包来调用Java编译器,但由于tools.jar不是标准的Java库,在使用时必须要设置这个jar的路径。而在Java SE6中为我们提供了标准的包来操作Java编译器,这就是javax.tools包。使用这个包,我们能不用将jar文件路径添加到classpath中了。

一、使用JavaCompiler接口来编译Java源程式

  使用Java API来编译Java源程式有非常多方法,目前让我们来看一种最简单的方法,通过JavaCompiler进行编译。

  我们能通过ToolProvider类的静态方法getSystemJavaCompiler来得到一个JavaCompiler接口的实例。

  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

JavaCompiler中最核心的方法是run。通过这个方法能编译java源程式。这个方法有3个固定参数和1个可变参数(可变参数是从Jave SE5开始提供的一个新的参数类型,用type… argu表示)。前3个参数分别用来为java编译器提供参数、得到Java编译器的输出信息及接收编译器的错误信息,后面的可变参数能传入一个或多个Java源程式文件。如果run编译成功,返回0。

  int run(InputStream in, OutputStream out, OutputStream err, String... arguments)

  如果前3个参数传入的是null,那么run方法将以标准的输入、输出代替,即System.in、System.out和System.err。如果我们要编译一个test.java文件,并将使用标准输入输出,run的使用方法如下:

  int results = tool.run(null, null, null, "test.java");

  下面是使用JavaCompiler的完整代码:

import java.io.*;
import javax.tools.*;

public class test_compilerapi
{
 public static void main(String args[]) throws IOException
 {
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  int results = compiler.run(null, null, null, "test.java");
  System.out.println((results == 0)?"编译成功":"编译失败");
  // 在程式中运行test
  Runtime run = Runtime.getRuntime();
  Process p = run.exec("java test");
  BufferedInputStream in = new BufferedInputStream(p.getInputStream());
  BufferedReader br = new BufferedReader(new InputStreamReader(in));
  String s;
  while ((s = br.readLine()) != null)
   System.out.println(s);
 }
}

public class test
{
 public static void main(String[] args) throws Exception

}

 编译成功的输出结果:

  编译成功
  JavaCompiler测试成功

  编译失败的输出结果:

test.java:9: 未找到符号
符号: 方法 printlnln(java.lang.String)
位置: 类 java.io.PrintStream
System.out.printlnln("JavaCompiler测试成功!");
^
1 错误
编译失败

二、使用StandardJavaFileManager编译Java源程式

  在第一部分我们讨论调用java编译器的最容易的方法。这种方法能非常好地工作,但他确不能更有效地得到我们所需要的信息,如标准的输入、输出信息。而在Java SE6中最佳的方法是使用StandardJavaFileManager类。这个类能非常好地控制输入、输出,并且能通过DiagnosticListener得到诊断信息,而DiagnosticCollector类就是listener的实现。

  使用StandardJavaFileManager需要两步。首先建立一个DiagnosticCollector实例及通过JavaCompiler的getStandardFileManager()方法得到一个StandardFileManager对象。最后通过CompilationTask中的call方法编译源程式。

  在使用这种方法调用Java编译时最复杂的方法就是getTask,下面让我们讨论一下getTask方法。这个方法有如下所示的6个参数。

getTask(Writer out,JavaFileManager fileManager,
DiagnosticListener<? super JavaFileObject> diagnosticListener,
Iterable<String> options,
Iterable<String> classes,
Iterable<? extends JavaFileObject> compilationUnits)

  这些参数大多数都可为null。他们的含义所下。

?out::用于输出错误的流,默认是System.err。

?fileManager::标准的文件管理。

?diagnosticListener: 编译器的默认行为。

?options: 编译器的选项

?classes:参和编译的class。

  最后一个参数compilationUnits不能为null,因为这个对象保存了你想编译的Java文件。

在使用完getTask后,需要通过StandardJavaFileManager的getJavaFileObjectsFromFiles或getJavaFileObjectsFromStrings方法得到compilationUnits对象。调用这两个方法的方式如下:.

Iterable<? extends JavaFileObject> getJavaFileObjectsFromFiles(
Iterable<? extends File> files)
Iterable<? extends JavaFileObject> getJavaFileObjectsFromStrings(
Iterable<String> names)

String[] filenames = …;
Iterable<? extends JavaFileObject> compilationUnits =
fileManager.getJavaFileObjectsFromFiles(Arrays.asList(filenames));

JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager,
diagnostics, options, null, compilationUnits);

  最后需要关闭fileManager.close();

  下面是个完整的演示程式。

import java.io.*;
import java.util.*;
import javax.tools.*;

public class test_compilerapi
{
 private static void compilejava() throws Exception
 {
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  // 建立DiagnosticCollector对象
  DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
  StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
  // 建立用于保存被编译文件名的对象
  // 每个文件被保存在一个从JavaFileObject继承的类中
  Iterable<? extends JavaFileObject> compilationUnits = fileManager
.getJavaFileObjectsFromStrings(Arrays asList("test3.java"));
  JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager,
diagnostics, null, null, compilationUnits);
  // 编译源程式
  boolean success = task.call();
  fileManager.close();
  System.out.println((success)?"编译成功":"编译失败");
 }
 public static void main(String args[]) throws Exception

}

如果想得到具体的编译错误,能对Diagnostics进行扫描,代码如下:

for (Diagnostic diagnostic : diagnostics.getDiagnostics())
System.out.printf(
"Code: %s%n" +
"Kind: %s%n" +
"Position: %s%n" +
"Start Position: %s%n" +
"End Position: %s%n" +
"Source: %s%n" +
"Message: %s%n",
diagnostic.getCode(), diagnostic.getKind(),
diagnostic.getPosition(), diagnostic.getStartPosition(),
diagnostic.getEndPosition(), diagnostic.getSource(),
diagnostic.getMessage(null));

  被编译的test.java代码如下:

public class test
{
 public static void main(String[] args) throws Exception
 {
  aa; //错误语句
  System.out.println("JavaCompiler测试成功!");
 }
}

  在这段代码中多写了个aa,得到的编译错误为:

Code: compiler.err.not.stmt
Kind: ERROR
Position: 89
Start Position: 89
End Position: 89
Source: test.java
Message: test.java:5: 不是语句
Success: false

  通过JavaCompiler进行编译都是在当前目录下生成.class文件,而使用编译选项能改动这个默认目录。编译选项是个元素为String类型的Iterable集合。如我们能使用如下代码在D盘根目录下生成.class文件。

Iterable<String> options = Arrays.asList("-d", "d:");
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager,
diagnostics, options, null, compilationUnits);

  在上面的例子中options处的参数为null,而要传递编译器的参数,就需要将options传入。

  有时我们编译一个Java源程式文件,而这个源程式文件需要另几个Java文件,而这些Java文件又在另外一个目录,那么这就需要为编译器指定这些文件所在的目录。

Iterable<String> options = Arrays.asList("-sourcepath", "d:src");

  上面的代码指定的被编译Java文件所依赖的源文件所在的目录。

三、从内存中编译

JavaCompiler不仅能编译硬盘上的Java文件,而且还能编译内存中的Java代码,然后使用reflection来运行他们。我们能编写一个JavaSourceFromString类,通过这个类能输入Java原始码。一但建立这个对象,你能向其中输入任意的Java代码,然后编译和运行,而且无需向硬盘上写.class文件。

import java.lang.reflect.*;
import java.io.*;
import javax.tools.*;
import javax.tools.JavaCompiler.CompilationTask;
import java.util.*;
import java.net.*;

public class test_compilerapi
{
 private static void compilerJava() throws Exception
 {
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
  // 定义一个StringWriter类,用于写Java程式
  StringWriter writer = new StringWriter();
  PrintWriter out = new PrintWriter(writer);
  // 开始写Java程式
  out.println("public class HelloWorld {");
  out.println(" public static void main(String args[]) {");
  out.println(" System.out.println("Hello, World");");
  out.println(" }");
  out.println("}");
  out.close();
  //为这段代码取个名子:HelloWorld,以便以后使用reflection调用
  JavaFileObject file = new JavaSourceFromString("HelloWorld", writer.toString());
  Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file);
  JavaCompiler.CompilationTask task = compiler.getTask(null, null,
   diagnostics, null, null, compilationUnits);
  boolean success = task.call();
  System.out.println("Success: " + success);
  // 如果成功,通过reflection执行这段Java程式
  if (success)
  {
   System.out.println("-----输出-----");
   Class.forName("HelloWorld").getDeclaredMethod("main", new Class[]
{ String[].class }).invoke(null, new Object[]
{ null });
   System.out.println("-----输出 -----");
  }
 }
 public static void main(String args[]) throws Exception

}
// 用于传递源程式的JavaSourceFromString类
class JavaSourceFromString extends SimpleJavaFileObject
{
 final String code;
 JavaSourceFromString(String name, String code)
 {
  super(URI.create("string:///" + name.replace(’.’, ’/’)+ Kind.SOURCE.extension), Kind.SOURCE);
  this.code = code;
 }
 @Override
 public CharSequence getCharContent(boolean ignoreEncodingErrors)
 {
  return code;
 }
}

 

 

 

public interface JavaCompiler
extends Tool, OptionChecker

从程序中调用 Java™ 编程语言编译器的接口。

编译过程中,编译器可能生成诊断信息(例如,错误消息)。如果提供了诊断侦听器,那么诊断信息将被提供给该侦听器。如果没有提供侦听器,那么除非另行指定,否则诊断信息将被格式化为未指定的格式,并被写入到默认输出 System.err。即使提供了诊断侦听器,某些诊断信息也可能不适合 Diagnostic,并将被写入到默认输出。

编译器工具具有关联的标准文件管理器,此文件管理器是工具本地的(或内置的)。可以通过调用 getStandardFileManager 获取该标准文件管理器。

只要满足下面方法详细描述中的任意附加需求,编译器工具就必须与文件管理器一起运行。如果没有提供文件管理器,则编译器工具将使用标准文件管理器,比如 getStandardFileManager 返回的标准文件管理器。

实现此接口的实例必须符合 Java Language Specification 并遵照 Java Virtual Machine 规范生成类文件。Tool 接口中定义了这些规范的版本。 此外,支持 SourceVersion.RELEASE_6 或更高版本的此接口的实例还必须支持注释处理。

编译器依赖于两种服务:诊断侦听器和文件管理器。虽然此包中的大多数类和接口都定义了编译器(和一般工具)的 API,但最好不要在应用程序中使用接口 DiagnosticListener、JavaFileManager、FileObject 和 JavaFileObject。应该实现这些接口,用于为编译器提供自定义服务,从而定义编译器的 SPI。

此包中有很多类和接口,它们被设计用于简化 SPI 的实现,以自定义编译器行为:

StandardJavaFileManager
    实现此接口的每个编译器都提供一个标准的文件管理器,以便在常规文件上进行操作。StandardJavaFileManager 接口定义了从常规文件创建文件对象的其他方法。

    标准文件管理器有两个用途:

        * 自定义编译器如何读写文件的基本构建块
        * 在多个编译任务之间共享

    重新使用文件管理器可能会减少扫描文件系统和读取 jar 文件的开销。标准文件管理器必须与多个顺序编译共同工作,尽管这样做并不能减少开销,下例是建议的编码模式:

Java代码

1. Files[] files1 = ...; // input for first compilation task   
2.   Files[] files2 = ...; // input for second compilation task   
3.   
4.   JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();   
5.   StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);   
6.   
7.   Iterable<? extends JavaFileObject> compilationUnits1 =   
8.   fileManager.getJavaFileObjectsFromFiles(Arrays.asList(files1));   
9.   compiler.getTask(null, fileManager, null, null, null, compilationUnits1).call();   
10.   
11.   Iterable<? extends JavaFileObject> compilationUnits2 =   
12.   fileManager.getJavaFileObjects(files2); // use alternative method   
13.   // reuse the same file manager to allow caching of jar files   
14.   compiler.getTask(null, fileManager, null, null, null, compilationUnits2).call();   
15.   
16.   fileManager.close();  
  Files[] files1 = ...; // input for first compilation task
    Files[] files2 = ...; // input for second compilation task
 
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
 
    Iterable<? extends JavaFileObject> compilationUnits1 =
    fileManager.getJavaFileObjectsFromFiles(Arrays.asList(files1));
    compiler.getTask(null, fileManager, null, null, null, compilationUnits1).call();
 
    Iterable<? extends JavaFileObject> compilationUnits2 =
    fileManager.getJavaFileObjects(files2); // use alternative method
    // reuse the same file manager to allow caching of jar files
    compiler.getTask(null, fileManager, null, null, null, compilationUnits2).call();
 
    fileManager.close();


 


DiagnosticCollector
    用于将诊断信息收集在一个列表中,例如:

Java代码

1. Iterable<? extends JavaFileObject> compilationUnits = ...;   
2.     JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();   
3.     DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();   
4.     StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);   
5.     compiler.getTask(null, fileManager, diagnostics, null, null, compilationUnits).call();   
6.   
7.     for (Diagnostic diagnostic :diagnostics.getDiagnostics())   
8.     System.out.format("Error on line %d in %d%n",   
9.     diagnostic.getLineNumber()   
10.     diagnostic.getSource().toUri());   
11.   
12.     fileManager.close();  
Iterable<? extends JavaFileObject> compilationUnits = ...;
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
    compiler.getTask(null, fileManager, diagnostics, null, null, compilationUnits).call();
 
    for (Diagnostic diagnostic :diagnostics.getDiagnostics())
    System.out.format("Error on line %d in %d%n",
    diagnostic.getLineNumber()
    diagnostic.getSource().toUri());
 
    fileManager.close();


 

ForwardingJavaFileManager、ForwardingFileObject 和 ForwardingJavaFileObject
    子类化不可用于重写标准文件管理器的行为,因为标准文件管理器是通过调用编译器上的方法创建的,而不是通过调用构造方法创建的。应该使用转发(或委托)。允许自定义行为时,这些类使得将多个调用转发到给定文件管理器或文件对象变得容易。例如,考虑如何将所有的调用记录到 JavaFileManager.flush():

Java代码

1. final Logger logger = ...;   
2.     Iterable<? extends JavaFileObject> compilationUnits = ...;   
3.     JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();   
4.     StandardJavaFileManager stdFileManager = compiler.getStandardFileManager(null, null, null);   
5.     JavaFileManager fileManager = new ForwardingJavaFileManager(stdFileManager) {   
6.     public void flush() {   
7.     logger.entering(StandardJavaFileManager.class.getName(), "flush");   
8.     super.flush();   
9.     logger.exiting(StandardJavaFileManager.class.getName(), "flush");   
10.                }   
11.            };   
12.     compiler.getTask(null, fileManager, null, null, null, compilationUnits).call();  
final Logger logger = ...;
    Iterable<? extends JavaFileObject> compilationUnits = ...;
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager stdFileManager = compiler.getStandardFileManager(null, null, null);
    JavaFileManager fileManager = new ForwardingJavaFileManager(stdFileManager) {
    public void flush() {
    logger.entering(StandardJavaFileManager.class.getName(), "flush");
    super.flush();
    logger.exiting(StandardJavaFileManager.class.getName(), "flush");
               }
           };
    compiler.getTask(null, fileManager, null, null, null, compilationUnits).call();


 


SimpleJavaFileObject
    此类提供基本文件对象实现,该实现可用作创建文件对象的构建块。例如,下例显示了如何定义表示存储在字符串中的源代码的文件对象:

Java代码

1.   /**  
2. * A file object used to represent source coming from a string.  
3. */  
4. public class JavaSourceFromString extends SimpleJavaFileObject {   
5.            /**  
6. * The source code of this "file".  
7. */  
8. final String code;   
9.   
10.            /**  
11. * Constructs a new JavaSourceFromString.  
12. * @param name the name of the compilation unit represented by this file object  
13. * @param code the source code for the compilation unit represented by this file object  
14. */  
15. JavaSourceFromString(String name, String code) {   
16. super(URI.create("string:///" + name.replace('.','/') + Kind.SOURCE.extension),   
17. Kind.SOURCE);   
18. this.code = code;   
19.            }   
20.   
21. @Override  
22. public CharSequence getCharContent(boolean ignoreEncodingErrors) {   
23. return code;   
24.            }   
25.        }  
      /**
    * A file object used to represent source coming from a string.
    */
    public class JavaSourceFromString extends SimpleJavaFileObject {
               /**
    * The source code of this "file".
    */
    final String code;
 
               /**
    * Constructs a new JavaSourceFromString.
    * @param name the name of the compilation unit represented by this file object
    * @param code the source code for the compilation unit represented by this file object
    */
    JavaSourceFromString(String name, String code) {
    super(URI.create("string:///" + name.replace('.','/') + Kind.SOURCE.extension),
    Kind.SOURCE);
    this.code = code;
               }
 
    @Override
    public CharSequence getCharContent(boolean ignoreEncodingErrors) {
    return code;
               }
           }


  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
"C:\Program Files\Java\jdk-1.8\bin\java.exe" -Dmaven.multiModuleProjectDirectory=F:\workmode\h5xjxj\ech-log-server\ech-log-api -Djansi.passthrough=true -Dmaven.home=F:\dev_software\apache-maven-3.6.3 -Dclassworlds.conf=F:\dev_software\apache-maven-3.6.3\bin\m2.conf "-Dmaven.ext.class.path=F:\idea2023\IntelliJ IDEA 2023.1.2\plugins\maven\lib\maven-event-listener.jar" "-javaagent:F:\idea2023\IntelliJ IDEA 2023.1.2\lib\idea_rt.jar=53993:F:\idea2023\IntelliJ IDEA 2023.1.2\bin" -Dfile.encoding=UTF-8 -classpath F:\dev_software\apache-maven-3.6.3\boot\plexus-classworlds-2.6.0.jar;F:\dev_software\apache-maven-3.6.3\boot\plexus-classworlds.license org.codehaus.classworlds.Launcher -Didea.version=2023.1.2 -s C:\Users\田文成\.m2\settings_XJ_git.xml -Dmaven.repo.local=F:\dev_software\repository\localRepository\localRepository install [INFO] Scanning for projects... [INFO] [INFO] -----------------------< com.ai.ecs:ech-log-api >----------------------- [INFO] Building ech-log-api 0.0.1-SNAPSHOT [INFO] --------------------------------[ jar ]--------------------------------- Downloading from nexus1: http://mgr.devstone.cn:18080/nexus/content/groups/public/org/apache/maven/plugins/maven-compiler-plugin/2.5.1/maven-compiler-plugin-2.5.1.pom [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 22.280 s [INFO] Finished at: 2023-07-12T16:30:43+08:00 [INFO] ------------------------------------------------------------------------ [ERROR] Plugin org.apache.maven.plugins:maven-compiler-plugin:2.5.1 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-compiler-plugin:jar:2.5.1: Could not transfer artifact org.apache.maven.plugins:maven-compiler-plugin:pom:2.5.1 from/to nexus1 (http://mgr.devstone.cn:18080/nexus/content/groups/public): Transfer failed for http://mgr.devstone.cn:18080/nexus/content/groups/public/org/apache/maven/plugins/maven-compiler-plugin/2.5.1/maven-compiler-plugin-2.5.1.pom: Connect to mgr.devstone.cn:18080 [mgr.devstone.cn/218.94.91.233] failed: Connection timed out: connect -> [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginResolutionException 刚导入项目依赖报错
最新发布
07-13

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值