11 November 2017

Java 9 Modules

What is a Java Module:

Java 9 has introduced modules.Module is nothing but a set of packages.
A new java file module-info.java in every module tells the following
1.Required packages for a modules
2.Exported packages from module.
Tools can generate this file, when we create a java modular application.

So the current access specifier of class "public" can have 3 definitions based on module-info.java.

Public class in a package
1.Can't be accessed outside the module if it is not exported.
Thus JDK encapsulates internal APIs.
2.Can be accessed outside the module if it is exported.
3.Can be accessed to some modules outside the module and can't be accessed by some modules outside the module.

Why we need --What are the advantages:

1.All the public classes can't be accessed outside the module,if module-info.java defined to
not to be accessed.Public classes of JDK internal APIs can't be accessed outside.So provides security improvement.

2.Java9 JDK has removed rt.jar and introduced 95 smaller modules.User can import the required module.Since there is no need to add big jars like rt.jar,which was essential to add java runtime libraries,the application size will be small

3.It will restrict to not to write packages with same name in two modules.
It will throw runtimeexception.So no split packages

Example:

“java.base” module is the base module.
module-info.java for java.base
module java.base {
    exports java.io;
    exports java.lang;
    exports java.math;
    exports java.net;
}
Every module requires java.base module.New folder in JDK jmods folder has all the modules and it looks like





No comments: