Java Modular System

Source: Internet
Author: User

Java Modular System

Java modular systems have gone through a long time since they were proposed until late 2014 to final with JSRJSR-376), and this Part may appear in Java 9. However, no prototype can be used for a long time. In September 11, the early build version released by OpenJDK finally included the Jigsaw project.

Yesterday, my colleague Paul Bakker discussed the Java modular system on JavaZone. The entire discussion is based on the JSR-376 requirement document and some valuable information around it. When we proposed this report at the beginning of the year, we were confident that we could present a prototype at this meeting, but things were not shown as expected. Now the prototype will be released after our report. This also means that some of the content in the report is a bit outdated, but the main idea is still very new. If you have no idea about the Java modular system solution, we recommend that you read our report before reading this article. Our report introduces the current solution and further compares it with OSGi.

Why use a module?

What is a module? Why do we need them? If you want to have an in-depth discussion, please read "State of the module system" or take a look at our report. For those who are not familiar with this section, here is the comment version of Cliff.

We all know that Java has jar files. However, in fact, these are only compressed files that contain some class classes. These jar packages contain some package packages ). When you use different jar packages to run applications, a more complex program also applies.) You need to put them in the specified class path. Then pray silently. There is no effective tool to help you know whether you have put all the jar packages required by the application into the class path. Or you may inadvertently put the same class file in different jar packages) into the class path. Class path disasters are similar to DLL disasters. This can cause a bad running condition. At the same time, we cannot know which classes are included in the jar. From the JRE perspective, only a bunch of class files are known. In fact, jar packages are mutually dependent, but such dependencies cannot be recorded in data files. Ideally, you can hide the implementation of class files in the jar package, but provide some public APIs. A modular system is proposed in Java to solve these problems:

  • The module becomes the first part to be considered. It can split the implementation details and only expose the required interfaces.

  • The module accurately describes the interfaces they can provide and their requirements are partially dependent ). Therefore, we can clarify and process dependencies during the development process.

The module system greatly improves the maintainability, reliability, and security of Large-Scale Systems. At least JDK itself lacks such a system. With such a module system, the module diagram can be automatically built. This figure only contains the modules required when your application is running.

Install JDK 9 Preview

If you want to write sample code in person, you need to install the early build version of JDK 9 that contains the Jigsaw prototype. On OSX, You need to decompress the document and then move the extracted directory to the Library/Java/JavaVirtualMachines/directory. Then you need to set the environment variable and point the JAVA_HOME environment variable to the JDK9 directory. I used a very easy-to-use setjdk script, through which I can switch the commands installed in Java in the Command window. You may be reluctant to use this early build version as your Java installation version. You can use java-version to confirm that the installation is complete. The output is shown below:

1

2

3

java version "1.9.0-ea"

Java(TM) SE Runtime Environment (build 1.9.0-ea-jigsaw-nightly-h3337-20150908-b80)

Java HotSpot(TM) 64-Bit Server VM (build 1.9.0-ea-jigsaw-nightly-h3337-20150908-b80, mixed mode)

As long as the output contains Jigsaw, you can continue. The sample code following the article can be downloaded from the https://github.com/sandermak/jigsaw-firstlook.

A simple example

You can still use jdk9. But obviously we want to adopt the module approach. So we will create a project that contains two modules: Module 1 uses the code in Module 2.

The first thing to do is to build our project and split the two modules into good regions. The module then needs to add metadata as a module-info.java file. Our example is constructed as follows:

1

2

3

4

5

6

7

src

  module1

     module-info.java

     comtestTestClassModule1.java

  module2

     module-info.java

     commoretestTestClassModule2.java

Next, we will introduce the package) the top layers of module1 and module2), which have been built before. In these module directories, you can see that the module-info.java file is under the root directory. Note that both classes are in the display named package.

Please refer to the code of TestClassModule1:

1

2

3

4

5

6

7

8

9

10

11

12

13

package com.test;

import com.moretest.TestClassModule2;

public class TestClassModule1 {

   public static void main(String[] args) {

     System.out.println("Hi from " + TestClassModule2.msg());

   }

}

It looks very common, right? The module is not involved here, But TestClassModule2 is imported. The main function then calls the msg () method.

1

2

3

4

5

6

7

8

9

10

11

package com.moretest;

public class TestClassModule2 {

   public static String msg() {

     return "from module 2!";

   }

}

So far, the module-info.java is still empty.

Compile the Java Module

Now proceed to the next step: compile our module and associate the source file. To do this, we will introduce a new javac compilation parameter:

1

javac -modulesourcepath src -d mods $(find src -name '*.java')

When using the preceding statement, we assume that the command program is already in the upper-level directory of the src folder. -The modulesourcepath parameter changes javac from the Traditional compilation mode to the module mode. -D indicates the output directory of the compiled module. Javac will output these modules in the form of non-packaged files. If we want to use these modules in the form of jars, we need a separate step.

So what will happen when we call the above javac command line? Compilation error!

1

2

src/module1/module-info.java:1: error: expected 'module'

src/module2/module-info.java:1: error: expected 'module'

An empty module-info.java file causes this error. Therefore, some new keywords will be introduced into these files, which are very important parts of the module. The scope of these keywords is part of the definition of the module-info.java. You can also use a module-type variable in the java source file.

We used the minimum description and updated the module description file:

1

module module1 { }

Then Module 2:

1

module module2{ }

Now, the module has been named accurately, but it does not contain any other data. Re-compilation will lead to new errors:

1

src/module1/com/test/TestClassModule1.java:3: error: TestClassModule2 is not visible because package com.moretest is not visible

Encapsulation appears! By default, classes or other types inside the module are hidden externally. This is why javac does not allow TestClassModule2, even if it is a public class. If we still use the compilation based on the traditional class path, everything will work normally. Of course, we can also solve this problem by explicitly exposing TestClassModule2 to the outside. The following changes are necessary for the module-info.java in module2:

1

2

3

4

5

module module2 {

  exports com.moretest;

}

This is not enough. If you compile the modified Code, you will get the same error. That's because although module2 has exposed all the public types of the required packages), module1 has not declared its dependency on module2. We can also change the module1 module-info.java file to solve this problem:

1

2

3

4

5

module module1 {

   requires module2;

}

You can specify a name to indicate dependencies on other modules, even though these modules are exported as packages. There are still many things to say in this regard, but I don't want to discuss it in the preliminary introduction. After completing this step, we successfully compiled multi-module projects with Jigsaw for the first time. If you open the/MoD directory, you can see that the compiled items are neatly divided into two directories. This is successful!

Run modular code

Compilation is not fun. We hope the application can run. Fortunately, JRE and JDK already support module Association in this prototype. This application can be started by specifying the module path instead of the class path:

1

java -mp mods -m module1/com.test.TestClassModule1

We direct the module path to the MOD folder, which is the place where the output module is written during javac compilation. -M indicates the module to be started at first, through which other modules can be started gradually. We also added the name of the startup class to be called during initialization. The running result is as follows:

1

Hi from from module 2!

Future

This section gives you a preliminary understanding of what modules in Java 9 can do. This part still requires more exploration. Just like packaging: In addition to jar packages, there will be a new form called jmod. This modular system also includes a service layer, which can bind service providers and service users through interfaces. This can be viewed as a reverse control: the module system acts as a service registration management role. Another value to expect is how the JDK itself will use a modular system for modularization. This may support some very good technologies, such as creating a runtime image. This image can only include the JDK and the modules required by your application. Benefits: Taking up less space and providing more options for overall program optimization. These prospects are bright.

Next I will try to port a simple OSGi application that will use some modules and services) to the Java 9 module system. Stay tuned!

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.