Getting return values from a compiled string which contains java codes in a java program using javaCompiler

StackOverflow https://stackoverflow.com/questions/22148257

  •  19-10-2022
  •  | 
  •  

Question

I have been able to successfully call javaCompiler and even compiled a string that contains java codes as shown below.

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");
}

}

The compiled class is even appearing in my bin folder. However i wanted to know if i could get the returned value directly from the compiler itself?

No correct solution

OTHER TIPS

You can try to use Eclipse compiler

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

This blog post might be useful.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top