java - 使用 javaCompiler 从包含 java 程序中的 java 代码的编译字符串中获取返回值

标签 java jakarta-ee

我已经能够成功调用javaCompiler,甚至编译了一个包含java代码的字符串,如下所示。

public class CompilerAPITest {
final Logger logger = Logger.getLogger(CompilerAPITest.class.getName()) ;

/**Java source code to be compiled dynamically*/
static String sourceCode = "package com.accordess.ca; class DynamicCompilationHelloWorld{ public static String main (String args[]){ String str=\"The return value\"; return str ;}}";



/**
 * Does the required object initialization and compilation.
 */
public void doCompilation (){
    /*Creating dynamic java source code file object*/
    SimpleJavaFileObject fileObject = new DynamicJavaSourceCodeObject ("com.accordess.ca.DynamicCompilationHelloWorld", sourceCode) ;
    JavaFileObject javaFileObjects[] = new JavaFileObject[]{fileObject} ;

    /*Instantiating the java compiler*/
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    /**
     * Retrieving the standard file manager from compiler object, which is used to provide
     * basic building block for customizing how a compiler reads and writes to files.
     * 
     * The same file manager can be reopened for another compiler task. 
     * Thus we reduce the overhead of scanning through file system and jar files each time 
     */
    StandardJavaFileManager stdFileManager = compiler.getStandardFileManager(null, Locale.getDefault(), null);

    /* Prepare a list of compilation units (java source code file objects) to input to compilation task*/
    Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(javaFileObjects);

    /*Prepare any compilation options to be used during compilation*/
    //In this example, we are asking the compiler to place the output files under bin folder.
    String[] compileOptions = new String[]{"-d", "bin"} ;
    Iterable<String> compilationOptionss = Arrays.asList(compileOptions);

    /*Create a diagnostic controller, which holds the compilation problems*/
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();

    /*Create a compilation task from compiler by passing in the required input objects prepared above*/
    CompilationTask compilerTask = compiler.getTask(null, stdFileManager, diagnostics, compilationOptionss, null, compilationUnits) ;

    //Perform the compilation by calling the call method on compilerTask object.
    boolean status = compilerTask.call();

    if (!status){//If compilation error occurs
        /*Iterate through each compilation problem and print it*/
        for (Diagnostic diagnostic : diagnostics.getDiagnostics()){
            System.out.format("Error on line %d in %s", diagnostic.getLineNumber(), diagnostic);
        }
    }
    try {
        stdFileManager.close() ;//Close the file manager
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public static void main(String args[]){
    new CompilerAPITest ().doCompilation() ;
    System.out.println("Compilation is running");
}

}

编译后的类甚至出现在我的 bin 文件夹中。但是我想知道是否可以直接从编译器本身获取返回值?

最佳答案

您可以尝试使用Eclipse编译器

http://www.eclipse.org/jdt/core/index.php

这个blog post可能有用。

关于java - 使用 javaCompiler 从包含 java 程序中的 java 代码的编译字符串中获取返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22148257/

相关文章:

Java - JFormattedTextField 不允许首次尝试输入

java - 如何在java中提取两个指定索引之间的列表的较小列表

java.lang.Exception : WEB0113

java - 如何使用接口(interface)和 JPA

删除 ArrayList 时出现 Java ConcurrentModificationException

尝试写入 excel 文件时出现 java.lang.NullPointerException :

java - 我如何创建一个每 0.1 秒运行一次并且可以向其中传递一个数组的可执行文件

jakarta-ee - 如何找到 netbeans RSVP 教程文件

java - 从另一个 Maven 模块引用接口(interface)的实现

java - Glassfish 在后台运行