Complete guide to modules in java

Dsforgood
2 min readJan 31, 2022

With the release of java 9 modularity was introduced in to java, in this article we will discuss about all that you need to know about it. Java platform module system (JPMS) or java modules is a ground breaking addition to java. Modularity brings lot of changes to how we organize our code.

Factors leading to Java modules

Before java modules there was no way of strongly encapsulating and restricting our code. We use packages with access modifiers to restrict access but, this is not efficient. People access internal packages directly which may cause security issues. Another factor is there was no way of grouping related packages. Also we use to put all the resources (XML files, Images) in to root folder path and access them but, we cannot group these resources.

Java modules definition and details

We can define a java module as Reusable group of related packages, as well as resources. Modularity adds a higher level of aggregation above packages. Modules help in strongly encapsulating the code. We can ship required images and XML files with the module that needs it, making our projects much easier to manage. Using java modules we can control which packages are exposed and also we can control the reflection on the classes.

Modules implementation

Modules are implemented by keeping a module descriptor (Module-info.java) in the root of source directory. In it we can define everything related to a module. We can name a module in this descriptor. Please go through the following list of directives that can be included in the module descriptor.

· requires : it allows to declare module dependencies. Adds compile and run time dependency.

· requires static : it adds a compile time only dependency

· requires transitive : helps in adding transitive dependency

· exports : To expose all public members of a package.

· export to : We can list all the modules to which our package is exposed.

· uses : we can designate the service that our module consumes.

· provides with : to use module as a service provider.

· open : to grant permission for reflection on classes

· opens : to allow reflection only on specific packages

· opens to : selectively opening our module to a list of modules

Java modules a final thought

So we have understood basic details and directives of java modules. Java modules is supported by all the IDE’s and build tools such as maven. So please take time in understanding this feature. If you are interested in learning java 17 I have a complete course for you please click here -> https://www.udemy.com/course/java-17-complete-course/?referralCode=C1A5CE9D4178AB159247

--

--

Dsforgood

We are a bunch of data science enthusiasts simplifying concepts and ideas in technology for common readers. We believe in using data science for good!