Java thousand asked _08jdk detailed (008) _ Through the code how to compile Java files

Source: Internet
Author: User
Tags iterable

Click to enter _ more _java thousand ask

1. How to compile Java files by code

The compiler is a command-line tool (the JDK's own compilation tool, Javac, for Javac see here: What Javac is), but it can also be invoked using the API (the General IDE uses this set of APIs to encapsulate its own compilation capabilities). The compiler follows the Java language Specification (the Java Language SPECIFICATION,JLS) and the Java Virtual Machine specification (the Java Vsan Specification,jvms).
After Java 6, a standard package was provided to manipulate the Java compiler, which is the Javax.tools package. We use the APIs in this package and other auxiliary packages to customize our own compilers. Through the source code of the Toolprovider class, we can see that javax.tools the API in this package eventually calls the Java compiler through the Com.sun.tools.javac package in Tools.jar.

There are three ways to compile Java in code, and you can use these methods flexibly to DIY your own compilers:

by Javacompiler.run ()
The simplest usage is to use the Javacompiler class's Run method, with the first 3 parameters: input information, output information, error information, and, if NULL, the default is: System.in, System.out, System.err. The last parameter is the command text after Javac, such as incoming Test.java, which is equivalent to executing Javac Test.java at the terminal.

For example:

publicclasspublicstaticvoidmain(String[] args) throws Exception {        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();        int run = compiler.run(nullnullnull"-version");        System.out.println("===" + run);    }}

Execution result (default printing in System.out because the output information is not specified):

Javac 1.7.0_79
===0

compiling code on the hard drive via Javacompiler.gettask ()
Using the Javacompiler.run method is very simple, but it does not get the information we need more efficiently. In general we will use the Standardjavafilemanager class (JDK 6 or above), this class can control the input, output, and can get diagnostic information through Diagnosticlistener, And the Diagnosticcollector class is the implementation of listener (listening).

The concrete examples are as follows:

 Public classTest { Public Static void Main(string[] args) throws Exception {Test.compiler ();} Public Static void compiler() throws IOException {Javacompiler compiler = Toolprovider.getsystemjavacompiler ();//Establish Diagnosticcollector objectDiagnosticcollector Diagnostics =NewDiagnosticcollector (); Standardjavafilemanager FileManager = Compiler.getstandardfilemanager (Diagnostics,NULL,NULL);//Create source file object, each file is saved in a class inherited from Javafileobjectiterable<? Extends javafileobject> compilationunits = filemanager.getjavafileobjectsfromstrings (Arrays. AsList ("/users/sunjie/desktop/works/workspace/my-test/src/com/test/test.java"));//Options command line optioniterable<string> options = Arrays.aslist ("-D","/users/sunjie/desktop/works/workspace/my-test/src/com/test/classes");//The specified path must be present, Javac does not create the folder itselfJavacompiler.compilationtask task = Compiler.gettask (NULL, FileManager, diagnostics, Options,NULL, compilationunits);//Compile source programBoolean success = Task.call ();        Filemanager.close (); System. out. println (Success)?"Compile succeeded":"Compilation failed");//Print information         for(ObjectObject: Diagnostics.getdiagnostics ()) {Diagnostic Diagnostic = (Diagnostic)Object; System. out. printf ("Code:%s%n"+"Kind:%s%n"+"Position:%s%n"+"Start Position:%s%n"+"End Position:%s%n"+"Source:%s%n"+"Message:%s%n", Diagnostic.getcode (), Diagnostic.getkind (), Diagnostic.getposition (), Diagnostic.getstartposition (), Diagnostic.getendposition (), Diagnostic.getsource (), Diagnostic.getmessage (NULL)); }}}

The results of the operation are as follows:

Compilation succeeded

The Com/test/test.class file will be found under the corresponding path (test package com.test, so the com/test/path is automatically generated in the corresponding directory).

compiling in-memory code by Javacompiler. Gettask ()
Javacompiler not only compiles the Java files on the hard disk, but also compiles the in-memory Java code and then uses reflection to run them. We can write a javasourcefromstring class that allows you to enter Java source code through this class.

The concrete examples are as follows:

 Public  class Test {     Public Static voidMain (string[] args) throws Exception {Test.compiler2 (); }? Public Static voidCompiler2 () throws IOException, Illegalaccessexception, IllegalArgumentException, InvocationTargetException, No Suchmethodexception, SecurityException, classnotfoundexception {javacompiler compiler = Toolprovider.getsystemjava        Compiler (); Diagnosticcollector Diagnostics =NewDiagnosticcollector ();//define a StringWriter class for writing Java programsStringWriter writer =NewStringWriter (); PrintWriter out =NewPrintWriter (writer);//Start writing Java programsOut.println ("public class HelloWorld {"); Out.println ("public static void Main (String args[]) {"); Out.println ("System.out.println (\" Hello, world\ ");"); Out.println (" }"); Out.println ("}");        Out.close (); Standardjavafilemanager FileManager = Compiler.getstandardfilemanager (Diagnostics,NULL,NULL);//Take a name for this code: HelloWorldSimplejavafileobject file = (NewTest ()).NewJavasourcefromstring ("HelloWorld", writer.tostring ()); Iterable compilationunits = arrays.aslist (file);//Options command line optioniterable<string> options = Arrays.aslist ("-D","/users/sunjie/desktop/works/workspace/my-test/src/com/test/classes");//The specified path must be present, Javac does not create the folder itselfJavacompiler.compilationtask task = Compiler.gettask (NULL, FileManager, diagnostics, Options,NULL, compilationunits);BooleanSuccess = Task.call (); SYSTEM.OUT.PRINTLN (Success)?"Compile succeeded":"Compilation failed"); }//Javasourcefromstring class for passing the source program     class javasourcefromstring extends simplejavafileobject {        FinalString Code; Javasourcefromstring (string name, string code) {Super(Uri.create ("string:///"+ Name.replace ('. ','/') + Kind.SOURCE.extension), kind.source); This. Code = Code; } @Override PublicCharsequence Getcharcontent (BooleanIgnoreencodingerrors) {returnCode }    }}

The results of the operation are as follows:

Compilation succeeded

The Helloworld.class file is found under the corresponding path.

Java thousand asked _08jdk detailed (008) _ Through the code how to compile Java files

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.