Dynamic compilation of JAVA programs

Source: Internet
Author: User

[Reseller Note] For many application systems, dynamic loading and execution classes and code snippets are often required, which facilitates deployment simplicity and system design flexibility. This article provides a comprehensive introduction, which is worth your reference.

In Sun JDK 1.2 and later versions, it contains a group of APIs that can compile and execute Java code at runtime. These APIs are included in the tools. jar class library. This function allows Java programs to dynamically compile and execute Small code blocks during runtime. In some cases, this function makes the Java application architecture more flexible and open.

This article assumes that the reader has installed and configured Sun JDK 1.2 or later on the computer, and has some knowledge about javac compiler commands.

  Use a compiler in a Java program
Suppose you want to use the javac command to compile the Test. java file in the/home/mytest directory, and set the class file to be stored in the/home/mytest/classes path. Enter the following command:

Javac-d/home/mytest/classes Test. java

To achieve the same purpose, you can also use a Java compiler API provided by Sun. It is also easy to use. The core code segment is as follows:

  1. ...
  2.   String[] Args =New String[] {"-D", "/homemytestclasses", "Test. java "};
  3. Int status = javac. compile (args );
  4. ...


The javac compilation tool is installed in the/bin directory of the JDK root directory and is responsible for compiling the source code into the bytecode running on JVM. In fact, we often use the javac compilation tool in the/bin directory to compile Java source files. If you dynamically compile arbitrary Java statements in a Java program, the use of this external javac compiler is not flexible enough. Although you can use the Runtime class to execute an external command, if you want to know whether the code is compiled and what error occurs during compilation, use the exec () the method is very difficult to implement.

In Sun's JDK 1.2 and later versions, the/lib path of the JDK installation path contains a tool. jar file, which contains a complete compiler package. Com. sun. tools. javac. Main is the Main class entry of the compiler. If you are familiar with the use of the javac compiler command line, it is easy to understand how to use this class. The compile (String [] p) method executes the compilation action. The parameter p is a String array used to store the Parameter options of the javac command. An Int value is returned for the compiled status, the corresponding values are shown in the following table:

Table status parameters and corresponding values

EXIT_ OK 0

EXIT_ERROR 1

EXIT_CMDERR 2

EXIT_SYSERR 3

EXIT_ABNORMAL 4



   Compile and execute Java statements during Program Execution

From the above section, we have basically learned how to dynamically compile a Java file. So how to dynamically compile the specified Java statement during runtime? Here is a tip.

Assume that the Java statements to be dynamically compiled are as follows:

  1.   System. Out. println ("Hello, This runtime code !");


The compiler does not support compiling a single Java statement. The compiled object must be. java is a suffix and has a valid structure class source program file. Therefore, you need to transform this statement into a complete class and put this statement into the main method for testing.

  1.   Public Class<Temporary class file name> {
  2.   Public Static VoidMain (String[] Args)Throws Exception{
  3.   System. Out. println ("Hello, This runtime code !");
  4. }
  5. }


In this way, the code to be dynamically compiled has been dynamically assembled into the above Code by the program. The preparation work is not over yet, but it seems that the work tends to be slightly complicated. Because the above Code is still stored in the memory, the compiler seems more interested in a hard disk file. We need to reference the java. io. File class (JDK 1.2 or above) and create a temporary File to store the content of the above Code. The static method createTempFile () of the java. io. File class ensures that the created File names are non-duplicated, which increases the flexibility of this program. Flexibility depends on the policies applied to the system architecture.

System. getProperty ("user. dir") is used to obtain the current path, which serves as the directory for storing temporary files.

  1. File file;
  2. File = File. createTempFile ("JavaRuntime", ". java ",NewFile (System. GetProperty ("user. dir ")));
  3.   StringFilename = file. getName ();
  4.   StringClassname = getClassName (filename );
  5.   // Output code to a file
  6. PrintWriter out =NewPrintWriter (NewFileOutputStream (file ));
  7. Out. println ("Public Class"+ Classname +" {"};
  8. Out. println ("... code ..");
  9. Out. println ("}");
  10.   // Close the file stream
  11. Out. flush ();
  12. Out. close ();

We agree that the temporary file name to be created will be suffixed with "JavaRuntime" (which can be any name), and the suffix will end with ". java. A Java source file to be compiled has been dynamically generated. Next, create a Main instance from the com. sun. tools. javac package and call the javac. compile () method to compile the temporary file:

  1. PrivateStaticCom. sun. tools. javac. Main javac =NewCom. sun. tools. javac. Main ();
  2.   String[] Args =New String[] {"-D ",System. GetProperty ("user. dir"), filename };
  3. Int status = javac. compile (args );


Assuming that the temporary file has passed the compiler syntax verification and other verification, the compilation is successful (the value of status is equal to 0, see the previous table), and a Java class file will be added to the running directory of the current program. We will simulate the execution of the Code to be dynamically compiled by executing this Java class file.

Java provides the ability to load classes at runtime, dynamically identifying and calling class constructor methods, class fields, and class methods. Java. lang. reflect. Method implements the Member interface. You can call the interface Method to obtain the name and modifier of the Method class. Methods such as getRuturnType (), getParameterTypes (), and getExeptionTypess () return the construction information of the represented method. Another important feature of Method is that you can call invoke () to execute this Method (for detailed usage, you can view the java. lang. reflect package documentation ). The following code creates a java. lang. reflect. Method class Method and calls the getMethod () Method to obtain the ing of the assembled main Method. The Code is as follows:

  1.   
Related Article

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.