javax.tools.JavaCompiler.getTask()方法的使用及代码示例

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

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

JavaCompiler.getTask介绍

[英]Creates a future for a compilation task with the given components and arguments. The compilation might not have completed as described in the CompilationTask interface.

If a file manager is provided, it must be able to handle all locations defined in StandardLocation.

Note that annotation processing can process both the compilation units of source code to be compiled, passed with the compilationUnits parameter, as well as class files, whose names are passed with the classesparameter.
[中]为具有给定组件和参数的编译任务创建未来。编译可能没有按照CompilationTask界面中的描述完成。
如果提供了文件管理器,它必须能够处理StandardLocation中定义的所有位置。
请注意,注释处理既可以处理要编译的源代码的编译单元(通过compilationUnits参数传递),也可以处理类文件(其名称通过classesparameter传递)。

代码示例

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

@Override
public Class<?> doCompile(String name, String sourceCode) throws Throwable {
  int i = name.lastIndexOf('.');
  String packageName = i < 0 ? "" : name.substring(0, i);
  String className = i < 0 ? name : name.substring(i + 1);
  JavaFileObjectImpl javaFileObject = new JavaFileObjectImpl(className, sourceCode);
  javaFileManager.putFileForInput(StandardLocation.SOURCE_PATH, packageName,
      className + ClassUtils.JAVA_EXTENSION, javaFileObject);
  Boolean result = compiler.getTask(null, javaFileManager, diagnosticCollector, options,
      null, Arrays.asList(javaFileObject)).call();
  if (result == null || !result) {
    throw new IllegalStateException("Compilation failed. class: " + name + ", diagnostics: " + diagnosticCollector);
  }
  return classLoader.loadClass(name);
}

代码示例来源: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: 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/incubator-dubbo

@Override
public Class<?> doCompile(String name, String sourceCode) throws Throwable {
  int i = name.lastIndexOf('.');
  String packageName = i < 0 ? "" : name.substring(0, i);
  String className = i < 0 ? name : name.substring(i + 1);
  JavaFileObjectImpl javaFileObject = new JavaFileObjectImpl(className, sourceCode);
  javaFileManager.putFileForInput(StandardLocation.SOURCE_PATH, packageName,
      className + ClassUtils.JAVA_EXTENSION, javaFileObject);
  Boolean result = compiler.getTask(null, javaFileManager, diagnosticCollector, options,
      null, Arrays.asList(javaFileObject)).call();
  if (result == null || !result) {
    throw new IllegalStateException("Compilation failed. class: " + name + ", diagnostics: " + diagnosticCollector);
  }
  return classLoader.loadClass(name);
}

代码示例来源: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: ltsopensource/light-task-scheduler

public Class<?> doCompile(String name, String sourceCode) throws Throwable {
  int i = name.lastIndexOf('.');
  String packageName = i < 0 ? "" : name.substring(0, i);
  String className = i < 0 ? name : name.substring(i + 1);
  JavaFileObjectImpl javaFileObject = new JavaFileObjectImpl(className, sourceCode);
  javaFileManager.putFileForInput(StandardLocation.SOURCE_PATH, packageName,
      className + JAVA_EXTENSION, javaFileObject);
  Boolean result = compiler.getTask(null, javaFileManager, diagnosticCollector, options,
      null, Collections.singletonList(javaFileObject)).call();
  if (result == null || !result) {
    throw new IllegalStateException("Compilation failed. class: " + name + ", diagnostics: " + diagnosticCollector);
  }
  return classLoader.loadClass(name);
}

代码示例来源: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();
}

代码示例来源:origin: ltsopensource/light-task-scheduler

public Class<?> doCompile(String name, String sourceCode) throws Throwable {
  int i = name.lastIndexOf('.');
  String packageName = i < 0 ? "" : name.substring(0, i);
  String className = i < 0 ? name : name.substring(i + 1);
  JavaFileObjectImpl javaFileObject = new JavaFileObjectImpl(className, sourceCode);
  javaFileManager.putFileForInput(StandardLocation.SOURCE_PATH, packageName,
      className + JAVA_EXTENSION, javaFileObject);
  Boolean result = compiler.getTask(null, javaFileManager, diagnosticCollector, options,
      null, Collections.singletonList(javaFileObject)).call();
  if (result == null || !result) {
    throw new IllegalStateException("Compilation failed. class: " + name + ", diagnostics: " + diagnosticCollector);
  }
  return classLoader.loadClass(name);
}

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

/**
 * Compiles a single class and loads the class using a new class loader.
 *
 * @param className class to compile.
 * @param sourceCode source code of the class to compile.
 * @return loaded class
 * @throws Exception
 */
public static Class<?> compile(String className, SimpleJavaFileObject sourceCode) throws Exception {
  ClassFile classFile = new ClassFile(className);
  Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(sourceCode);
  AppClassLoader cl = new AppClassLoader(Thread.currentThread().getContextClassLoader());
  FileManager fileManager = new FileManager(javac.getStandardFileManager(null, null, null), Arrays.asList(classFile), cl);
  JavaCompiler.CompilationTask task = javac.getTask(null, fileManager, null, getClOptions(), null, compilationUnits);
  task.call();
  return cl.loadClass(className);
}

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

public CompilationResult compile(final List<StringWrappingJavaFile> javaFiles) {
  DiagnosticsHolder holder = new DiagnosticsHolder();
  CompilationTask task = compiler.getTask(null, null, holder, options, null, javaFiles);
  if (task.call()) {
    return new CompilationResult(new URLClassLoader(compilationDirectoryUrls), holder.diagnostics);
  } else {
    return new CompilationResult(holder.diagnostics);
  }
}

代码示例来源:origin: com.h2database/h2

/**
 * Compile using the standard java compiler.
 *
 * @param packageName the package name
 * @param className the class name
 * @param source the source code
 * @return the class
 */
Class<?> javaxToolsJavac(String packageName, String className, String source) {
  String fullClassName = packageName + "." + className;
  StringWriter writer = new StringWriter();
  try (JavaFileManager fileManager = new
      ClassFileManager(JAVA_COMPILER
        .getStandardFileManager(null, null, null))) {
    ArrayList<JavaFileObject> compilationUnits = new ArrayList<>();
    compilationUnits.add(new StringJavaFileObject(fullClassName, source));
    // cannot concurrently compile
    synchronized (JAVA_COMPILER) {
      JAVA_COMPILER.getTask(writer, fileManager, null, null,
          null, compilationUnits).call();
    }
    String output = writer.toString();
    handleSyntaxError(output);
    return fileManager.getClassLoader(null).loadClass(fullClassName);
  } catch (ClassNotFoundException | IOException e) {
    throw DbException.convert(e);
  }
}

代码示例来源:origin: google/error-prone

public Result run(
   String[] args,
   JavaFileManager fileManager,
   List<JavaFileObject> javaFileObjects,
   Iterable<? extends Processor> processors) {
  JavaCompiler compiler = new BaseErrorProneJavaCompiler(scannerSupplier);
  try {
   CompilationTask task =
     compiler.getTask(
       errOutput,
       fileManager,
       diagnosticListener,
       ImmutableList.copyOf(args),
       null /*classes*/,
       javaFileObjects);
   if (processors != null) {
    task.setProcessors(processors);
   }
   return task.call() ? Result.OK : Result.ERROR;
  } catch (InvalidCommandLineOptionException e) {
   errOutput.print(e);
   errOutput.flush();
   return Result.CMDERR;
  }
 }
}

代码示例来源: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: google/error-prone

private void checkWellFormed(Iterable<JavaFileObject> sources, List<String> args) {
  createAndInstallTempFolderForOutput(fileManager);
  JavaCompiler compiler = JavacTool.create();
  OutputStream outputStream = new ByteArrayOutputStream();
  List<String> remainingArgs = null;
  try {
   remainingArgs = Arrays.asList(ErrorProneOptions.processArgs(args).getRemainingArgs());
  } catch (InvalidCommandLineOptionException e) {
   fail("Exception during argument processing: " + e);
  }
  CompilationTask task =
    compiler.getTask(
      new PrintWriter(
        new BufferedWriter(new OutputStreamWriter(outputStream, UTF_8)),
        /*autoFlush=*/ true),
      fileManager,
      null,
      remainingArgs,
      null,
      sources);
  boolean result = task.call();
  assertWithMessage(
      String.format(
        "Test program failed to compile with non Error Prone error: %s", outputStream))
    .that(result)
    .isTrue();
 }
}

代码示例来源: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: kaaproject/kaa

options = newOptions;
CompilationTask task = compiler.getTask(null, javaDynamicManager,
  diagnostics, options, null, sources);
boolean result = task.call();
if (!result) {
 throw new JavaDynamicException("The compilation failed",

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

public boolean compile() throws Exception {
  String fullName = clsNode.getFullName();
  String code = clsNode.getCode().toString();
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  fileManager = new ClassFileManager(compiler.getStandardFileManager(null, null, null));
  List<JavaFileObject> jFiles = new ArrayList<>(1);
  jFiles.add(new CharSequenceJavaFileObject(fullName, code));
  CompilationTask compilerTask = compiler.getTask(null, fileManager, null, null, null, jFiles);
  return Boolean.TRUE.equals(compilerTask.call());
}

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

CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits);
boolean success = task.call();
for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
 System.out.println(diagnostic.getCode());

代码示例来源: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: hibernate/hibernate-orm

private void compileSources(List<String> options,
      JavaCompiler compiler,
      DiagnosticCollector<JavaFileObject> diagnostics,
      StandardJavaFileManager fileManager,
      Iterable<? extends JavaFileObject> compilationUnits) {
    JavaCompiler.CompilationTask task = compiler.getTask(
        null, fileManager, diagnostics, options, null, compilationUnits
    );
    task.call();
    for ( Diagnostic<?> diagnostic : diagnostics.getDiagnostics() ) {
      log.debug( diagnostic.getMessage( null ) );
    }
  }
}

相关文章