[Java] Switch java version installed by SDKMAN when changing directory

1 minute read

By using .sdkmanrc, you can switch the version of java, scala, etc. installed by SDKMAN when changing directories like direnv. Since it was added relatively recently, SDKMAN must be updated to the latest version (5.8.3 at the time of writing) in order to use it.

generate .sdkmanrc

Run sdk env init in the directory where you want to specify the version.

$ cd sdkenv-test/
$ sdk env init
.sdkmanrc created.

The .sdkmanrc is generated and looks like this:

$ cat .sdkmanrc
# Enable auto-env through the sdkman_auto_env config
# Add key=value pairs of SDKs to use below
java=8.0.202.j9-adpt

Configuration

Specify the version you want to use for the generated .sdkmanrc.

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

Set sdkman_auto_env=true in ~/.sdkman/etc/config. By setting sdkman_auto_env=true, it will be switched automatically when you move to a directory like direnv.

Restart the shell.

$ exec $SHELL -l

Execution example

$ cd sdkenv-test/

Using java version 13.0.2.j9-adpt in this shell.

If sdkman_auto_env=false you need to switch manually

If sdkman_auto_env=false is set, switching to the directory containing .sdkmanrc does not switch automatically. You have to run sdk env to switch.

$ cd sdkenv-test/
$ java --version
openjdk 14.0.1 2020-04-14
OpenJDK Runtime Environment AdoptOpenJDK (build 14.0.1+7)
Eclipse OpenJ9 VM AdoptOpenJDK (build openj9-0.20.0, JRE 14 Linux amd64-64-Bit Compressed References 20200416_44 (JIT enabled, AOT enabled)
OpenJ9-05fa2d361
OMR-d4365f371
JCL-5757187cae based on jdk-14.0.1+7)
$ sdk env

Using java version 13.0.2.j9-adpt in this shell.