javax.tools.JavaCompiler类的使用及代码示例

x33g5p2x  于2022-01-21 转载在 其他  
字(24.7k)|赞(0)|评价(0)|浏览(176)

本文整理了Java中javax.tools.JavaCompiler类的一些代码示例,展示了JavaCompiler类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。JavaCompiler类的具体详情如下:
包路径:javax.tools.JavaCompiler
类名称:JavaCompiler

JavaCompiler介绍

[英]Interface to invoke Java™ programming language compilers from programs.

The compiler might generate diagnostics during compilation (for example, error messages). If a diagnostic listener is provided, the diagnostics will be supplied to the listener. If no listener is provided, the diagnostics will be formatted in an unspecified format and written to the default output, which is System.err unless otherwise specified. Even if a diagnostic listener is supplied, some diagnostics might not fit in a Diagnostic and will be written to the default output.

A compiler tool has an associated standard file manager, which is the file manager that is native to the tool (or built-in). The standard file manager can be obtained by calling #getStandardFileManager.

A compiler tool must function with any file manager as long as any additional requirements as detailed in the methods below are met. If no file manager is provided, the compiler tool will use a standard file manager such as the one returned by #getStandardFileManager.

An instance implementing this interface must conform to The Java™ Language Specification and generate class files conforming to The Java™ Virtual Machine Specification. The versions of these specifications are defined in the Tool interface. Additionally, an instance of this interface supporting javax.lang.model.SourceVersion#RELEASE_6or higher must also support javax.annotation.processing.

The compiler relies on two services: DiagnosticListener and JavaFileManager. Although most classes and interfaces in this package defines an API for compilers (and tools in general) the interfaces DiagnosticListener, JavaFileManager, FileObject, and JavaFileObject are not intended to be used in applications. Instead these interfaces are intended to be implemented and used to provide customized services for a compiler and thus defines an SPI for compilers.

There are a number of classes and interfaces in this package which are designed to ease the implementation of the SPI to customize the behavior of a compiler: StandardJavaFileManager Every compiler which implements this interface provides a standard file manager for operating on regular java.io.File. The StandardJavaFileManager interface defines additional methods for creating file objects from regular files.

The standard file manager serves two purposes:

  • basic building block for customizing how a compiler reads and writes files
  • sharing between multiple compilation tasks

Reusing a file manager can potentially reduce overhead of scanning the file system and reading jar files. Although there might be no reduction in overhead, a standard file manager must work with multiple sequential compilations making the following example a recommended coding pattern:

File[] files1 = ... ; // input for first compilation task 
File[] files2 = ... ; // input for second compilation task 
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); 
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); 
 Iterable compilationUnits1 = 
fileManager.getJavaFileObjectsFromFiles( 
java.util.Arrays#asList(files1)); 
compiler.getTask(null, fileManager, null, null, null, compilationUnits1).call(); 
 Iterable 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 Used to collect diagnostics in a list, for example:

Iterable compilationUnits = ...; 
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); 
 DiagnosticCollector diagnostics = new DiagnosticCollector();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 %s%n", 
diagnostic.getLineNumber(), 
diagnostic.getSource().toUri()); 
fileManager.close();

ForwardingJavaFileManager, ForwardingFileObject, and ForwardingJavaFileObject Subclassing is not available for overriding the behavior of a standard file manager as it is created by calling a method on a compiler, not by invoking a constructor. Instead forwarding (or delegation) should be used. These classes makes it easy to forward most calls to a given file manager or file object while allowing customizing behavior. For example, consider how to log all calls to JavaFileManager#flush:

final  
java.util.logging.Logger logger = ...; 
 Iterable compilationUnits = ...; 
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); 
StandardJavaFileManager stdFileManager = compiler.getStandardFileManager(null, null, null); 
JavaFileManager fileManager = new ForwardingJavaFileManager(stdFileManager) { 
public void flush() throws IOException { 
logger.entering(StandardJavaFileManager.class.getName(), "flush"); 
super.flush(); 
logger.exiting(StandardJavaFileManager.class.getName(), "flush"); 
} 
}; 
compiler.getTask(null, fileManager, null, null, null, compilationUnits).call();

SimpleJavaFileObject This class provides a basic file object implementation which can be used as building block for creating file objects. For example, here is how to define a file object which represent source code stored in a string:

/ 
* 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( 
java.net.URI#create("string:///" + name.replace('.','/') + Kind.SOURCE.extension), 
Kind.SOURCE); 
this.code = code; 
} 
 @Override 
public CharSequence getCharContent(boolean ignoreEncodingErrors) { 
return code; 
} 
}

[中]调用Java的接口™ 程序设计语言编译器。
编译器可能在编译期间生成诊断(例如,错误消息)。如果提供了诊断侦听器,则将向侦听器提供诊断。如果未提供侦听器,诊断将以未指定的格式格式化,并写入默认输出,即系统。除非另有规定,否则为错误。即使提供了诊断侦听器,某些诊断也可能不适合诊断,并将写入默认输出。
编译器工具具有关联的标准文件管理器,该文件管理器是该工具(或内置)的本机文件管理器。可以通过调用#getStandardFileManager获得标准文件管理器。
只要满足以下方法中详述的任何附加要求,编译器工具必须与任何文件管理器一起工作。如果未提供文件管理器,编译器工具将使用标准文件管理器,如#getStandardFileManager返回的文件管理器。
实现此接口的实例必须符合Java规范™ 语言规范并生成符合Java规范的类文件™ 虚拟机规范。这些规范的版本在工具界面中定义。此外,该接口的一个实例支持javax。朗。模型。SourceVersion#RELEASE 或更高版本还必须支持javax。注释。处理。
编译器依赖于两个服务:DiagnosticListener和JavaFileManager。尽管此包中的大多数类和接口都为编译器(以及一般的工具)定义了API,但DiagnosticListener、JavaFileManager、FileObject和JavaFileObject接口并不打算在应用程序中使用。相反,这些接口旨在实现并用于为编译器提供定制服务,从而为编译器定义SPI。
这个包中有许多类和接口,旨在简化SPI的实现,以自定义编译器的行为:StandardJavaFileManager实现此接口的每个编译器都提供一个标准文件管理器,用于在常规java上操作。木卫一。文件StandardJavaFileManager接口定义了从常规文件创建文件对象的其他方法。
标准文件管理器有两个用途:
*用于自定义编译器如何读取和写入文件的基本构造块
*在多个编译任务之间共享
重用文件管理器可能会减少扫描文件系统和读取jar文件的开销。尽管开销可能不会减少,但标准文件管理器必须使用多个顺序编译,使以下示例成为推荐的编码模式:

File[] files1 = ... ; // input for first compilation task 
File[] files2 = ... ; // input for second compilation task 
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); 
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); 
 Iterable compilationUnits1 = 
fileManager.getJavaFileObjectsFromFiles( 
java.util.Arrays#asList(files1)); 
compiler.getTask(null, fileManager, null, null, null, compilationUnits1).call(); 
 Iterable 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用于在列表中收集诊断信息,例如:

Iterable compilationUnits = ...; 
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); 
 DiagnosticCollector diagnostics = new DiagnosticCollector();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 %s%n", 
diagnostic.getLineNumber(), 
diagnostic.getSource().toUri()); 
fileManager.close();

ForwardingJavaFileManager、ForwardingFileObject和ForwardingJavaFileObject子类化不可用于覆盖标准文件管理器的行为,因为它是通过调用编译器上的方法而不是调用构造函数创建的。相反,应该使用转发(或委托)。这些类可以轻松地将大多数调用转发到给定的文件管理器或文件对象,同时允许自定义行为。例如,考虑如何将所有调用记录到JavaFiMeMaGeer-SyfFLISH:<$$ 2 > SimuleJavaFieldObjor。该类提供了一个基本文件对象实现,它可以用作创建文件对象的构建块。例如,下面是如何定义表示存储在字符串中的源代码的文件对象:

/ 
* 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( 
java.net.URI#create("string:///" + name.replace('.','/') + Kind.SOURCE.extension), 
Kind.SOURCE); 
this.code = code; 
} 
 @Override 
public CharSequence getCharContent(boolean ignoreEncodingErrors) { 
return code; 
} 
}

代码示例

代码示例来源:origin: androidannotations/androidannotations

public CompileResult compileFiles(Collection<File> compilationUnits) {
  DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>();
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticCollector, null, null)) {
    CompilationTask task = compiler.getTask(null, fileManager, diagnosticCollector, compilerOptions, null, fileManager.getJavaFileObjectsFromFiles(compilationUnits));
    List<Processor> processors = new ArrayList<>();
    for (Class<? extends Processor> processorClass : processorsClasses) {
      try {
        processors.add(processorClass.newInstance());
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
    task.setProcessors(processors);
    task.call();
  } catch (IOException e) {
    // we should always be able to close the manager
  }
  return new CompileResult(diagnosticCollector.getDiagnostics());
}

代码示例来源:origin: apache/flink

private static int compileClass(File sourceFile) {
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  return compiler.run(null, null, null, "-proc:none", sourceFile.getPath());
}

代码示例来源:origin: apache/storm

/**
 * @return Whether compilation was successful.
 */
private boolean compileSourceCodeToByteCode(
  String className, String sourceCode, DiagnosticListener<JavaFileObject> diagnosticListener) {
  JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
  // Set up the in-memory filesystem.
  InMemoryFileManager fileManager =
    new InMemoryFileManager(javaCompiler.getStandardFileManager(null, null, null));
  JavaFileObject javaFile = new InMemoryJavaFile(className, sourceCode);
  // Javac option: remove these when the javac zip impl is fixed
  // (http://b/issue?id=1822932)
  System.setProperty("useJavaUtilZip", "true"); // setting value to any non-null string
  List<String> options = new LinkedList<>();
  // this is ignored by javac currently but useJavaUtilZip should be
  // a valid javac XD option, which is another bug
  options.add("-XDuseJavaUtilZip");
  // Now compile!
  JavaCompiler.CompilationTask compilationTask =
    javaCompiler.getTask(
      null, // Null: log any unhandled errors to stderr.
      fileManager,
      diagnosticListener,
      options,
      null,
      singleton(javaFile));
  return compilationTask.call();
}

代码示例来源:origin: Graylog2/graylog2-server

@NotNull
private Map<String, byte[]> compileFromSource(@NotNull String className, @NotNull String javaCode) {
  if (JAVA_COMPILER == null) {
    log.error("No compiler present, unable to compile {}", className);
    return Collections.emptyMap();
  }
  final InMemoryFileManager memoryFileManager = new InMemoryFileManager(JAVA_COMPILER.getStandardFileManager(null, null, null));
  List<Diagnostic> errors = Lists.newArrayList();
  JAVA_COMPILER.getTask(null, memoryFileManager, diagnostic -> {
    if (diagnostic.getKind() == Diagnostic.Kind.ERROR) {
      errors.add(diagnostic);
    }
  }, null, null, Collections.singleton(new JavaSourceFromString(className, javaCode))).call();
  Map<String, byte[]> result = memoryFileManager.getAllClassBytes();
  if (!errors.isEmpty()) {
    throw new PipelineCompilationException(errors);
  }
  return result;
}

代码示例来源:origin: stackoverflow.com

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> compilationUnits =
    fileManager.getJavaFileObjectsFromStrings(Arrays.asList(file));
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
compiler.getTask(null, fileManager, diagnostics, null, null, compilationUnits).call();
for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
  messages.add(diagnostic.getKind() + ":\t Line [" + diagnostic.getLineNumber() + "] \t Position [" + diagnostic.getPosition() + "]\t" + diagnostic.getMessage(Locale.ROOT) + "\n");

代码示例来源:origin: eclipse-vertx/vert.x

@Before
public void setUp() throws IOException {
 JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
 StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
 File output = new File("target/externals");
 output.mkdirs();
 fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singletonList(
   output));
 Iterable<? extends JavaFileObject> compilationUnits1 =
   fileManager.getJavaFileObjectsFromFiles(Collections.singletonList(
     new File("src/test/externals/MyVerticle.java")));
 compiler.getTask(null, fileManager, null, null, null, compilationUnits1).call();
}

代码示例来源:origin: stackoverflow.com

DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
    = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(helloWorldJava));
JavaCompiler.CompilationTask task = compiler.getTask(
  null, 
  fileManager, 
  compilationUnit);
if (task.call()) {
  for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
    System.out.format("Error on line %d in %s%n",
        diagnostic.getLineNumber(),
        diagnostic.getSource().toUri());

代码示例来源:origin: org.chtijbug.drools/drools-runtime-builder

protected void compileTarget(File targetDir) throws IOException {
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
  StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
  Collection allFiles = FileUtils.listFiles(targetDir, new String[]{"java"}, true);
  Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(allFiles);
  JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, null, null, compilationUnits);
  boolean status = task.call();
  if (!status) {
    /*Iterate through each compilation problem and print it*/
    for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
      logger.error("Error on line {} in {}", diagnostic.getLineNumber(), diagnostic);
    }
  }
  fileManager.close();
}

代码示例来源:origin: org.uberfire/uberfire-workbench-processors-tests

final String... compilationUnits) {
final DiagnosticCollector<JavaFileObject> diagnosticListener = new DiagnosticCollector<JavaFileObject>();
  final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  final StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticListener,
                                        null,
                                        null);
      fileManager.getJavaFileObjects(convertedCompilationUnits);
  final CompilationTask task = compiler.getTask(null,
                         fileManager,
                         diagnosticListener,
                         null,
                         compilationUnitsJavaObjects);
  task.setProcessors(Arrays.asList(annotationProcessor));
  task.call();
  fileManager.close();
} catch (IOException ioe) {
  fail(ioe.getMessage());
return diagnosticListener.getDiagnostics().stream().filter(p -> p.getKind() != Kind.NOTE).collect(Collectors.toList());

代码示例来源:origin: apache/geode

/**
 * Compile the provided class. The className may have a package separated by /. For example:
 * my/package/myclass
 *
 * @param className Name of the class to compile.
 * @param classCode Plain text contents of the class
 * @return The byte contents of the compiled class.
 */
public byte[] compileClass(final String className, final String classCode) throws IOException {
 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
 JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
 OutputStreamJavaFileManager<JavaFileManager> fileManager =
   new OutputStreamJavaFileManager<JavaFileManager>(
     javaCompiler.getStandardFileManager(null, null, null), byteArrayOutputStream);
 List<JavaFileObject> fileObjects = new ArrayList<JavaFileObject>();
 fileObjects.add(new JavaSourceFromString(className, classCode));
 List<String> options = Arrays.asList("-classpath", this.classPath);
 DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
 if (!javaCompiler.getTask(null, fileManager, diagnostics, options, null, fileObjects).call()) {
  StringBuilder errorMsg = new StringBuilder();
  for (Diagnostic d : diagnostics.getDiagnostics()) {
   String err = String.format("Compilation error: Line %d - %s%n", d.getLineNumber(),
     d.getMessage(null));
   errorMsg.append(err);
   System.err.print(err);
  }
  throw new IOException(errorMsg.toString());
 }
 return byteArrayOutputStream.toByteArray();
}

代码示例来源:origin: com.goldmansachs.jdmn/jdmn-core

javax.tools.JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticCollector, null, null);
fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton(classesDir));
};
Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file);
CompilationTask task = compiler.getTask(null, fileManager, diagnosticCollector, Arrays.asList(compileOptions), null, compilationUnits);
task.call();
List<Diagnostic<? extends JavaFileObject>> errors = diagnosticCollector.getDiagnostics().stream().filter(d -> d.getKind() == Diagnostic.Kind.ERROR).collect(Collectors.toList());
if (!errors.isEmpty()) {
  throw new DMNRuntimeException(errors.toString());
ClassLoader classLoader = fileManager.getClassLoader(StandardLocation.CLASS_OUTPUT);
return classLoader.loadClass(qualifiedClassName);

代码示例来源:origin: eclipse-vertx/vert.x

DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
if (javaCompiler == null) {
 throw new RuntimeException("Unable to detect java compiler, make sure you're using a JDK not a JRE!");
StandardJavaFileManager standardFileManager = javaCompiler.getStandardFileManager(null, null, null);
standardFileManager.setLocation(StandardLocation.SOURCE_PATH, Collections.singleton(javaSourceContext.getSourceRoot()));
fileManager = new MemoryFileManager(loader, standardFileManager);
JavaFileObject javaFile = standardFileManager.getJavaFileForInput(StandardLocation.SOURCE_PATH, resolveMainClassName(), Kind.SOURCE);
JavaCompiler.CompilationTask task = javaCompiler.getTask(null, fileManager, diagnostics, COMPILER_OPTIONS, null, Collections.singleton(javaFile));
boolean valid = task.call();
if (valid) {
 for (Diagnostic<?> d : diagnostics.getDiagnostics()) {
  String code = d.getCode();
  if (code == null || (!code.startsWith("compiler.warn.annotation.method.not.found") &&
    !"compiler.warn.proc.processor.incompatible.source.version".equals(code))) {
 for (Diagnostic<?> d : diagnostics.getDiagnostics()) {
  log.warn(d);

代码示例来源:origin: stackoverflow.com

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits);
boolean success = task.call();
for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
 System.out.println(diagnostic.getCode());
 System.out.println(diagnostic.getKind());
 System.out.println(diagnostic.getPosition());
 System.out.println(diagnostic.getStartPosition());
 System.out.println(diagnostic.getEndPosition());

代码示例来源:origin: neo4j/neo4j

private <T> T compile( String className, String source, CompilationListener<T> listener )
{
  JavaCompiler systemCompiler = ToolProvider.getSystemJavaCompiler();
  JavaFileManager manager = new InMemFileManager();
  DiagnosticCollector<JavaFileObject> diagnosticsCollector = new DiagnosticCollector<>();
  Iterable<? extends JavaFileObject> sources = Collections.singletonList( new InMemSource( className, source ) );
  CompilationTask task = systemCompiler.getTask( null, manager, diagnosticsCollector, null, null, sources );
  Boolean success = task.call();
  return listener.compiled( success, manager, diagnosticsCollector.getDiagnostics() );
}

代码示例来源:origin: stackoverflow.com

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromStrings(Arrays.asList("YouFileToCompile.java"));
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, null,
    null, compilationUnits);
boolean success = task.call();
fileManager.close();

代码示例来源:origin: hibernate/hibernate-orm

private void compile(List<File> sourceFiles) throws Exception {
  List<String> options = createJavaOptions();
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
  StandardJavaFileManager fileManager = compiler.getStandardFileManager( diagnostics, null, null );
  Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(
      sourceFiles
  );
  compileSources( options, compiler, diagnostics, fileManager, compilationUnits );
  compilationDiagnostics.addAll( diagnostics.getDiagnostics() );
  fileManager.close();
}

代码示例来源:origin: skylot/jadx

public static List<File> compile(List<File> files, File outDir, boolean includeDebugInfo) throws IOException {
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
  Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(files);
  StaticFileManager staticFileManager = new StaticFileManager(fileManager, outDir);
  List<String> options = new ArrayList<>();
  options.add(includeDebugInfo ? "-g" : "-g:none");
  options.addAll(COMMON_ARGS);
  CompilationTask task = compiler.getTask(null, staticFileManager, null, options, null, compilationUnits);
  Boolean result = task.call();
  fileManager.close();
  if (Boolean.TRUE.equals(result)) {
    return staticFileManager.outputFiles();
  }
  return Collections.emptyList();
}

代码示例来源:origin: neo4j/neo4j

@Override
  public Iterable<? extends ByteCodes> compile( List<JavaSourceFile> sourceFiles, ClassLoader loader )
      throws CompilationFailureException
  {
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();

    FileManager fileManager = new FileManager(
        compiler.getStandardFileManager( diagnostics, configuration.locale(), configuration.charset() ) );

    JavaCompiler.CompilationTask task = compiler.getTask(
        configuration.errorWriter(), fileManager, diagnostics, configuration.options(), null, sourceFiles );

    configuration.processors( task );
    if ( task.call() )
    {
      configuration.warningsHandler().handle( diagnostics.getDiagnostics() );
      return fileManager.bytecodes();
    }
    else
    {
      @SuppressWarnings( "unchecked" )
      List<Diagnostic<?>> issues = (List) diagnostics.getDiagnostics();
      throw new CompilationFailureException( issues );
    }
  }
}

代码示例来源:origin: apache/incubator-dubbo

public JdkCompiler() {
  options = new ArrayList<String>();
  options.add("-source");
  options.add("1.6");
  options.add("-target");
  options.add("1.6");
  StandardJavaFileManager manager = compiler.getStandardFileManager(diagnosticCollector, null, null);
  final ClassLoader loader = Thread.currentThread().getContextClassLoader();
  if (loader instanceof URLClassLoader
      && (!loader.getClass().getName().equals("sun.misc.Launcher$AppClassLoader"))) {
    try {
      URLClassLoader urlClassLoader = (URLClassLoader) loader;
      List<File> files = new ArrayList<File>();
      for (URL url : urlClassLoader.getURLs()) {
        files.add(new File(url.getFile()));
      }
      manager.setLocation(StandardLocation.CLASS_PATH, files);
    } catch (IOException e) {
      throw new IllegalStateException(e.getMessage(), e);
    }
  }
  classLoader = AccessController.doPrivileged(new PrivilegedAction<ClassLoaderImpl>() {
    @Override
    public ClassLoaderImpl run() {
      return new ClassLoaderImpl(loader);
    }
  });
  javaFileManager = new JavaFileManagerImpl(manager, classLoader);
}

代码示例来源:origin: jersey/jersey

/**
 * Compiles multiple source files at once.
 *
 * @param appClassLoader common class loader for the classes.
 * @param javaFiles source files to compile.
 * @throws Exception in case something goes wrong.
 */
public static void compile(AppClassLoader appClassLoader, List<JavaFile> javaFiles) throws Exception {
  List<ClassFile> classes = new LinkedList<>();
  for (JavaFile javaFile : javaFiles) {
    classes.add(new ClassFile(javaFile.getClassName()));
  }
  Iterable<? extends JavaFileObject> compilationUnits = javaFiles;
  FileManager fileManager = new FileManager(javac.getStandardFileManager(null, null, null), classes, appClassLoader);
  JavaCompiler.CompilationTask task = javac.getTask(null, fileManager, null, getClOptions(), null, compilationUnits);
  task.call();
}

相关文章