Computer >> Computer tutorials >  >> Programming >> Java

What is the use of a multi-version compatible jar in Java 9?


Multi-version compatible JAR function allows us to create the version of a class that we choose to use only when running library programs in a specific version of the Java environment. We can specify the compiled version through the "--release" parameter.

A specific change is that the "MANIFEST.MF" file in the "META-INF" directory has a new attribute as below

Multi-Release: true

There is a new version directory under the "META-INF" directory. If we want to support Java 9 version, there is a 9 directory under the versions directory.

multirelease.jar
├── META-INF
│   └── versions
│       └── 9
│           └── multirelease
│               └── Helper.class
├── multirelease
    ├── Helper.class
    └── Main.class


In the below example, we can use a multi-version compatible JAR function to generate two versions of the jar package from the "Test.java" file. One version is jdk 7, and another version is jdk 9, then we execute it in different environments.

First Step: Create a folder C:/test/java7/com/tutorialspoint, and create a "Test.java" file in this folder as below:

package com.tutorialspoint;

public class Test {
   public static void main(String args[]) {
      System.out.println("Inside Java 7");
   }
}

Second Step: Create a folder C:/test/java9/com/tutorialspoint, and create a "Test.java" file in this folder as below:

package com.tutorialspoint;

public class Test {
   public static void main(String args[]) {
      System.out.println("Inside Java 9");
   }
}


We can compile the code as below:

C:\test> javac --release 9 java9/com/tutorialspoint/Test.java
C:\test> javac --release 7 java7/com/tutorialspoint/Test.java


We can create a multi-version compatible jar package as below

C:\JAVA> jar -c -f test.jar -C java7 . --release 9 -C java9
Warning: entry META-INF/versions/9/com/tutorialspoint/Test.java, multiple resources with same name


Use JDK 7 to execute:

C:\JAVA> java -cp test.jar com.tutorialspoint.Test
Inside Java 7


Use JDK 9 to execute:

C:\JAVA> java -cp test.jar com.tutorialspoint.Test
Inside Java 9