Great Tool for Selecting the Java Version for OS X
Friday, March 20th, 2015One of the things that I've really missed in the latest version of Mac OS X is the utility to set the default version of the JDK to use. Well, with all the clojure coding I've been doing, I have typically stuck to JDK 1.7, but recently, the auto-updater from Oracle has them shipping JDK 1.8. Yet this doesn't effect the command-line utilities. This is a pain in the neck.
So first, I got JDK 1.7.0_75 on all my machines - it's going to be the last version of JDK 1.7 that I'll get as it's off the auto-updater. Then I was sure that everything was OK, I also got the complete JDK 1.8.0_40 - which is what the auto-updater downloaded for the JRE, but not the JDK. Yes, annoying.
At that point, I started googling about what to do. Turns out, JAVA_HOME is all I need to worry about. The java, jar, java apps in /usr/bin are all respectful of JAVA_HOME. Then I found this function that I added to my ~/.bashrc:
# # Clever trick to leverage the /usr/bin/java commands to take advantage # of the JAVA_HOME environment variable and the /usr/libexec/java_home # executable to change the JDK on-the-fly. This is so easy I'm amazed. # function removeFromPath() { export PATH=$(echo $PATH | sed -E -e "s;:$1;;" -e "s;$1:?;;") } function setjdk() { if [ $# -ne 0 ]; then removeFromPath '/System/Library/Frameworks/JavaVM.framework/Home/bin' if [ -n "${JAVA_HOME+x}" ]; then removeFromPath $JAVA_HOME fi export JAVA_HOME=`/usr/libexec/java_home -v $@` # export PATH=$JAVA_HOME/bin:$PATH fi } setjdk 1.7
At this point, I saw that the key command was /usr/libexec/java_home, and it had all the answeres I needed. I didn't need to update my PATH - just JAVA_HOME. I also could verify that I had all the versions of Java I needed:
$ /usr/libexec/java_home -V Matching Java Virtual Machines (7): 1.8.0_40, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_40.jdk/ Contents/Home 1.7.0_75, x86_64: "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_75.jdk/ Contents/Home 1.7.0_51, x86_64: "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/ Contents/Home 1.7.0_45, x86_64: "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_45.jdk/ Contents/Home 1.7.0_13, x86_64: "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_13.jdk/ Contents/Home 1.6.0_65-b14-466.1, x86_64: "Java SE 6" /System/Library/Java/JavaVirtualMachines/ 1.6.0.jdk/Contents/Home 1.6.0_65-b14-466.1, i386: "Java SE 6" /System/Library/Java/JavaVirtualMachines/ 1.6.0.jdk/Contents/Home
And then with a simple command - in the shell of my choice - I can set - and reset the JDK I use. It's very click:
$ setjdk 1.7 $ javac -version javac 1.7.0_75 $ setjdk 1.8 $ javac -version javac 1.8.0_40
Everything else works like a charm. This is a handy little tool to have, and I'm sure I'm going to use it often as I migrate from JDK 1.7 to 1.8.