1

I have the following (simplified) code, within my class, which invokes the Java Compiler to process a given source file:

package test;
import javax.tools.*;

public class SimpleCompileTest {
    public static void main(String[] args) {
        String fileToCompile = "MyClass.java";

        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        int compilationResult = compiler.run(null, null, null, fileToCompile);

        if(compilationResult == 0){
            System.out.println("Compilation is successful");
        } else {
            System.out.println("Compilation Failed");
        }
    }
}

The compilation succeeds, but now how can i get the result of MyClass.java, how to run this compiled code.

1

2 Answers 2

0
package javacompiler;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
public class COmpilerHello {
    public static void main(String[] args)
    {
        String s="C:/Users/MariaHussain/Desktop/hussi.java";
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        int result = compiler.run(System.in,System.out,System.err,s);
        System.out.println("Compile result code = " + result);
    }
}

see the various value of result variale like 0,1 2 show the comilation state , whether it is compiled or not

Sign up to request clarification or add additional context in comments.

Comments

0

get JavaFileManager, set location to save .class files and then load it via (custom) class loader:

StandardJavaFileManager stdFileManager = compiler.getStandardFileManager(null, Locale.getDefault(), null);

stdFileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File("classDir")));

 + custom classloader

Or without storing: JavaCompiler from JDK 1.6: how to write class bytes directly to byte[] array?

where you get pointed to: https://weblogs.java.net/blog/2008/12/17/how-compile-fly

where the main idea is to use custom MemoryFileManager as JavaFileManager.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.