Call the Java compiler from a Java class

2

So, this is what I would like to know is if I have to call the Java compiler from one running class to compile another and generate the .class from it.

How can I do this?

    
asked by anonymous 14.03.2016 / 14:07

2 answers

3

Use the method ToolProvider#getSystemJavaCompiler for get an instance of JavaCompiler .

Then you can compile classes using the template below (extracted from the documentation):

File[] fontes = ... ;
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> compilationUnits1 = 
    fileManager.getJavaFileObjectsFromFiles(Arrays.asList(fontes));
compiler.getTask(null, fileManager, null, null, null, compilationUnits1).call();
fileManager.close();

There are several other API points to explore, and I can say that it's not usually worth much of a fuss unless you're building an IDE or a new compiler for a dynamic language.

For the massive majority of everyday build tasks you should prefer a project lifecycle management tool such as Gradle, Maven, SBT or even Ant.

    
15.03.2016 / 05:50
1

Assuming you have JDK on your machine and that it is Windows, you can do something like:

 Process process = new ProcessBuilder("%JAVA_HOME%\bin\javac.exe","<caminho para o fonte>").start();

For a more general context you can also do this, which already "pulls" the environment that is being used to run the current application:

Runtime.getRuntime().exec("javac <caminho para o fonte>");
    
14.03.2016 / 14:20