Automatic switching of Java SDK versions

I’ve been using SdkMan! for a long time, it makes it quite easy to manage multiple versions of different frameworks. I’ve been almost exclusivly using it to manage Java SDK versions over the past years, and although I’m mostly writing code in Kotlin recently every now and then I’m also looking at Java based projects. Today I had a look at a project that was still based on Java 8. SDKMan! makes it easy to get the corresponding JDK installed and available. However, until now I used SDKMan! manually. That means I had to select to required Java version for the project by entering the command:

sdk use java 8.0.222.hs-adpt

Today I learned that you can automate this by adding an SDKMan! environment file to the project. You can do this by issuing the command:

sdk env init

You will then find a file named .sdkmanrc in the same folder, in which you can specify the required version, in my case it looks like this:

# Enable auto-env through the sdkman_auto_env config
# Add key=value pairs of SDKs to use below
java=8.0.222.hs-adpt

Now you can issue the command sdk env if you want to switch to this version, and if you want to go back to your default you can revert using the command skd env clear. We are only missing a small bit now: we want sdkman to automatically switch environments if we change into our folder. We can achieve this through a change in the SdkMan! configuration: in ~/.sdkman/etc/config you can set the sdk_auto_env option to true.

That’s it, SdkMan! will now automatically setup Java 8 when we change into the folder and revert to the default version if we leave the folder. Next order of business: make the project use a more recent version of Java! 🙂