Java 9: Multi-Release JAR Files, Part II

In Part I on multi release JAR Files, we learned what it is and why it is useful. In this part we will learn how to actually construct such a JAR and test it out.

For this demonstration we will be using just the command line as opposed to Maven or Gradle. Tooling support for Java 9 is still ramping up 🙂

in a src folder, we have two classes

public class Application {
   public static void main(String[] args) throws IOException {
      Generator gen = new Generator();
      System.out.println("Generated strings: " + gen.createStrings());
   }
}

and

public class Generator {
   public Set<String> createStrings() {
      Set strings = new HashSet();
      strings.add("Java");
      strings.add("7");
      return strings;
   }
}

Then in another src folder we have another implementation of the class using Java 9 features:

public class Generator {
   public Set<String> createStrings() {
      return Set.of("Java", "9");
   }
}

Finally, we need to specify a file containing a new manifest attribute to indicate that the JAR is a multi-release JAR. The manifest needs to include:

Multi-Release: true

And now, to compile! From the command line:

javac -d build -release 7 src/*.java
javac -d build/META-INF/versions/9 --release 9 src9/*.java
jar --create --file mrjar.jar --manifest MANIFEST.MF --main-class=Application -C build .

There are a couple things going on here: We need to compile in multiple phases like this because we literally need to generate different versions of bytecode and put it in different places. Also note that we are compiling with the new -release argument instead of -source and -target. Refer to JEP-247 for more details, but essentially it guarantees the class to be compatible with a given version of the JVM in a way that -source and -target can’t.

Finally, if we set our path to use the appropriate JVM, when running on Java 9 we see

java -jar mrjar.jar
Generated strings: [Java, 9]

But running the same JAR on Java 7 we see

java -jar mrjar.jar
Generated strings: [Java, 7]

Proving that a different class was used for each version of Java that was running it!

Admittedly this is still a bit crude, with the non-standard file locations and dropping to the command line to do everything. We will build up to a Gradle example soon!

Advertisements

2 Comments

Filed under Java 9

2 responses to “Java 9: Multi-Release JAR Files, Part II

  1. the option for compiling to older versions is –release and not -release

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s