Pragmatism in the real world

Using jenv to select Java version on macOS

When working on OpenWhisk, I discovered that it needed a different Java to the one I had installed. Looking around the Internet, I discovered jenv which shouldn’t have surprised me as I use pyenv and I’m aware of rbenv too.

As I use Homebrew, these are the commands I used.

Firstly install jenv, the latest Java (15 at this time) and any other versions you need. Java 8 and 12 in this example:

$ brew install jenv
$ brew install java
$ brew tap AdoptOpenJDK/openjdk
$ brew install --cask adoptopenjdk12
$ brew install --cask adoptopenjdk8

We now add jenv to our terminal by adding the following to .bash_profile:

export PATH="$HOME/.jenv/bin:$PATH"
eval "$(jenv init -)"

Restart your terminal to pick up the change.

The next step is to add our Java versions to jenv:

$ jenv add /Library/Java/JavaVirtualMachines/jdk-15.0.1.jdk/Contents/Home/
$ jenv add /Library/Java/JavaVirtualMachines/adoptopenjdk-12.jdk/Contents/Home/
$ jenv add /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home/

The exact versions depend on what you have installed. ls /Library/Java/JavaVirtualMachines/ will tell you.

Selecting the Java version

jenv’s versions will provide you a list of the available versions on your system:

$ jenv versions
* system (set by /Users/rob/.jenv/version)
  1.8
  1.8.0.275
  12
  12.0
  12.0.2
  15
  15.0
  15.0.1
  openjdk64-1.8.0.275
  openjdk64-12.0.2
  oracle64-15.0.1

Update: with newer version of jenv, use jenv local

I like to set a given Java version on a per-directory basis using jenv local. For example to set Java 12 for OpenWhisk, I navigate to ~/Project/openwhisk and type:

$ jenv version 12

This will create a .java-version file in the directory with the specified version.

Whenever you I navigate to this directory or a sub-directory of it, then jenv will ensure that Java 12 will be used.

Job done!

6 thoughts on “Using jenv to select Java version on macOS

  1. The 'brew cask install' command is now longer correct, it should be 'brew install –cask'

    The 'jenv version' command only gives you the current version. The command should be 'jenv local'.

  2. Hello, thanks for the tutorial! It helped alot :) I have a question, when I installed an adoptopen-jdk eg. version 14, why do i see other packages when i do a `jenv versions`? 14, 14.0, 14.0.2

  3. Looks like AdoptOpenJDK has been renamed, am getting this warning message:

    ▶ brew install –cask adoptopenjdk
    ==> Caveats
    Temurin is the official successor to this software:

    brew install –cask temurin

    adoptopenjdk has been officially discontinued upstream.
    It may stop working correctly (or at all) in recent versions of macOS.

  4. Awesome compilation. Works like a charm.

    In between, to jenv switch reflect in $JAVA_HOME
    jenv enable-plugin export

Comments are closed.