1

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?

user3371303
  • 43
  • 1
  • 4
  • What do you mean by the returned value? – Martin Serrano Mar 03 '14 at 13:45
  • I guess you OP want to execute the method and get the returned value – Kick Mar 03 '14 at 13:47
  • from the string to be executed, the main returns a string. i want to get that return value. static String sourceCode = "package com.accordess.ca; class DynamicCompilationHelloWorld{ public static String main (String args[]){ String str=\"The return value\"; return str ;}}"; Please help – user3371303 Mar 03 '14 at 15:45
  • Probably what you are looking for: http://stackoverflow.com/questions/12173294/compiling-fully-in-memory-with-javax-tools-javacompiler – Big Bad Baerni Mar 04 '14 at 09:20
  • @BigBadBaerni Thank you. it is actually what am trying to do, http://www.javablogging.com/dynamic-in-memory-compilation/ but trying the example to that link, am getting the following error Exception in thread “main” java.lang.NullPointerException at DynaCompTest.main(DynaCompTest.java:29) and this error corresponds to this code: JavaFileManager fileManager = new ClassFileManager(compiler.getStandardFileManager(null, null, null)); Can you help please? – user3371303 Mar 04 '14 at 20:41

1 Answers1

0

You can try to use Eclipse compiler

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

This blog post might be useful.

m-szalik
  • 3,178
  • 1
  • 18
  • 28
  • Can that be added to a java program? What am actually trying to do is that a user inputs a piece of java code from an interface in the form of plain text and am trying to compile it in java and return the output to the user. – user3371303 Mar 03 '14 at 13:47
  • Thank you. I will give it a try. – user3371303 Mar 03 '14 at 13:49