Calling the Java compiler from a Java class

Asked

Viewed 140 times

2

So, here’s the thing, I was wondering if I could call the Java compiler from one running class, to compile another one and generate the . her class.

How can I do that?

  • You want to run the javac command to compile your . java programmatically?

  • Take a look at the Javacc. I don’t know if this is exactly what you want.

2 answers

3

Use the method ToolProvider#getSystemJavaCompiler to obtain 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 in general it is not worth messing with unless you are building an IDE or a new compiler for a dynamic language.

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

1

Assuming you have JDK on your machine and it’s 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 way, that already "pulls" the environment that is being used to run the current application:

Runtime.getRuntime().exec("javac <caminho para o fonte>");
  • Is there no way to do this better in Java? Only in Gambi?

  • @Bigown An ugly solution and a decent.

  • 1

    Where’s the decent one? :)

  • @bigown Note that I didn’t say it was good. It’s only decent, does what he wants "on any platform". It will still have to make some logic to pull the location of the file, but as this was not specified is only the crucial part of the business.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.