Java 9 Multi-Release JARs
The Multi-Release JAR feature allows you to create different versions of classes that are used only when the library runs on specific Java environments.
Specify the compilation version with the --release
parameter.
The specific change is the addition of a new attribute in the META-INF directory's MANIFEST.MF file:
Multi-Release: true
Then, a new versions
directory is added under the META-INF directory. For support with Java 9, there will be a directory named 9
under the versions
directory.
multirelease.jar
├── META-INF
│ └── versions
│ └── 9
│ └── multirelease
│ └── Helper.class
├── multirelease
├── Helper.class
└── Main.class
In the following example, we use the Multi-Release JAR feature to generate two versions of the Tester.java file into a JAR, one for JDK 7 and another for JDK 9, and then execute them in different environments.
Step 1
Create a folder c:/test/java7/com/tutorialpro and create a Test.java file in this folder with the following code:
Example
package com.tutorialpro;
public class Tester {
public static void main(String[] args) {
System.out.println("Inside java 7");
}
}
Step 2
Create a folder c:/test/java9/com/tutorialpro and create a Test.java file in this folder with the following code:
Example
package com.tutorialpro;
public class Tester {
public static void main(String[] args) {
System.out.println("Inside java 9");
}
}
Compile the source code:
C:\test > javac --release 9 java9/com/tutorialpro/Tester.java
C:\JAVA > javac --release 7 java7/com/tutorialpro/Tester.java
Create a multi-release JAR:
C:\JAVA > jar -c -f test.jar -C java7 . --release 9 -C java9 .
Warning: entry META-INF/versions/9/com/tutorialpro/Tester.java,
multiple resources with same name
Execute with JDK 7:
C:\JAVA > java -cp test.jar com.tutorialpro.Tester
Inside Java 7
Execute with JDK 9:
C:\JAVA > java -cp test.jar com.tutorialpro.Tester
Inside Java 9