
#Java compiler code#
However, if you want the compiler to read source code from somewhere other than a disk file, you need to supply your own JavaFileObject subclass. Iterable fileObjects = fileManager.getJavaFileObjectsFromStrings(fileNames) For example, StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null) If you want the compiler to read source files from disk, you can ask the StandardJavaFileManager to translate the file name strings or File objects to JavaFileObject instances. For example, a sequence of options might be specified as Iterable options = Arrays.asList("-g", "-d", "classes") Īlternatively, you can use any collection class. You need to provide the last three arguments as Iterable objects.

#Java compiler install#
To listen to error messages, install a DiagnosticListener. A JavaFileObject can correspond to a disk file, or it can provide another mechanism for reading and writing its contents. It is responsible for determining JavaFileObject instances for source and class files. The location of source and class files is controlled by a JavaFileManager. Listen to error and warning messages as they occur during compilation.Control the placement of class files-for example, by storing them in a database.Control the source of program code-for example, by providing code in a string builder instead of a file.You can have even more control over the compilation process with a CompilationTask object. The remaining parameters of the run method are simply the arguments that you would pass to javac if you invoked it on the command line. (The run method is inherited from a generic Tool interface, which allows for tools that read input.)

As the compiler takes no console input, you can always leave it as null. The first parameter of the run method is an input stream.

You can set these parameters to null, in which case System.out and System.err are used. The compiler sends output and error messages to the provided streams. Int result = n(null, outStream, errStream, "-sourcepath", "src", "Test.java") Ī result value of 0 indicates successful compilation. Here is a sample call: JavaCompiler compiler = ToolProvider.getSystemJavaCompiler() As of Java SE 6, a public API for compilation is a part of the Java platform, and it is no longer necessary to use tools.jar. In the past, applications invoked the Java compiler by calling undocumented classes in the jdk /lib/tools.jar library.

Templating tools that process snippets of Java code, such as JavaServer Pages (JSP).There are quite a few tools that need to invoke the Java compiler, such as: Now we turn to a different scenario: Java programs that compile Java code.
#Java compiler how to#
In the preceding sections, you saw how to interact with code in a scripting language. Core Java, Volume II-Advanced Features, 9th Edition
