Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have the java8 code that uses Unsafe working on jdk8 and jdk9?

I am using sun.misc.Unsafe in my Java8 codebase. This does not work on Java9.

I would like to have the fix for Java9, but with the same codebase that runs on Java8. If I put module-info.java, it will not work, as my codebase is Java8.

What to do?

like image 202
igr Avatar asked Oct 18 '22 02:10

igr


1 Answers

Andreas comment points in the correct direction, you can make use of the Multi-Release JAR Files.

You can create a packaging such that the classes with code common to both the Java JDKs are in the root JAR while the one for which you need to overwrite the implementation is in both the root jar as well as META-INF/versions/9. As noted from the JEP:-

  • In a JDK that does not support MRJARs, only the classes and resources in the root directory will be visible.

  • In a JDK that does support MRJARs, the directories corresponding to any later Java platform release would be ignored; it would search for classes and resources first in the Java platform-specific directory corresponding to the currently-running major Java platform release version, then search those for lower versions, and finally the JAR root.

  • For example, on a Java 9 JDK, it would be as if there were a JAR-specific classpath containing first the version 9 files, and then the JAR root; on a Java 8 JDK, this classpath would contain only the JAR root.

Edit:- Here is a sample project for a similar packaging created with the help of a JetBrains blog using IntelliJ2017.3.

like image 142
Naman Avatar answered Oct 20 '22 22:10

Naman