Home > Software engineering >  Write a Java8 library which can use java9 features if running in Java9 or greater
Write a Java8 library which can use java9 features if running in Java9 or greater

Time:11-23

I want to write a java8 library and I have to compile it with java8 because it uses a ByteBuffer which has some nasty method signature change (which then throw the infamous error “method not found”).

However the new Java versions has some nice features that I’d like to use if those are available at runtime. For instance newer version of Java has Inflater.setValue(ByteBuffer) and Arrays.compareUnsigned that allow the application to run faster based on a benchmark I did.

How can I arrange a gradle project to use those features if are available considering that I have to build the project with JDK8?

I was thinking of creating 2 different libraries, one named -jdk8 and the second one with postfix jdk9 but I’d like to avoid too much duplicate code.

What’s the best practise?

Thank you.

CodePudding user response:

Don't cross the streams with different Java versions. Things tend to go haywire and have lots of unexpected behaviours, often they won't even compile.

enter image description here

If you really want to do things like this, you need to start to look at microservices architectures to give you this flexibility.

CodePudding user response:

Since Java 9 there is the possibility to create a multi release jar. In your library you can put different implementations into src/main/java and src/main/java9 for example. This way you don't have to create multiple projects of your library for different target java versions. You would have to compile the library with JDK 9 of course, but the project using your library should build then with JDK 8, because the library contains implementations for it.

  • Related