Despite what a lot of conference talks might lead you to think, far from every Java developer uses Docker on a daily basis, if at all. However, chances are high they work with a couple of different Java versions. This can be for different reasons:
- to check for version compatibility on the same app e.g. 7 vs 8
- to check for provider compatibility on the same app e.g. OpenJDK vs Oracle
- because different apps currently under development (or maintenance) require different Java versions
- because you want to play with the latest JDK version, but are stuck with Java 1.7 at work
To handle that requirement, the easy approach is to set the
JAVA_HOME environment variable when necessary, e.g.:
That works. But you have to remember the path to the required Java version every time you need to change. If there’s no such need, you must at least do it every time you open a new shell. Given the current faster release cycle of Java versions, the number of concurrent Java versions one is using is bound to increase even more in the next few years.
Other languages face the same issue. One of them is Ruby. To handle that, there’s a tool called rbenv. Wouldn’t it be nice if there was such a tool for Java? Well, there is.
jenv is exactly what you need if you need using different Java versions on the same machine.
- Install it
brew install jenv
It can alternatively be installed via
git clone. In that case, you should also manually update your system to point the
PATHto the executable.
- Register a JDK
jenv add /Library/Java/JavaVirtualMachines/jdk-9.0.4.jdk/Contents/Home
The output is something like:
oracle64-9.0.4 added 9.0.4 added 9.0 added
This is the only time when you’ll need to remember the path!
- List available JDKs
The output might be akin to (depending on the current state of your system):
* system 1.8 18.104.22.168 (set by /usr/local/var/jenv/version) 9.0 9.0.4 oracle64-22.214.171.124 oracle64-9.0.4
*points to the version in use in the current folder
- Set the default JDK
jenv global 1.8
- Override the JDK in use for the current folder
jenv local 9.0
This doesn’t stop here, though. Easier Java version handling is not useful, if it doesn’t integrate with tools used daily, such as Maven.
jenv offers integration with those tools through plugins. For example, to force
mvn to use the version defined through
jenv enable-plugin maven
Plugins are available for Ant, Groovy, Spring Boot, and even SBT (and some more)!
If you need to juggle through different Java versions,
jenv is perhaps not a life-saver but for sure a time-saver.