I'm trying out OpenJDK 7 developer preview for Mac OS X and came across a blog post by Matt Raible, giving a useful hint for how to switch between JDK 6 and JDK 7 easily.
He suggested the following bash function (to be added to .bash_profile):
function setjdk() {
if [ $# -ne 0 ]; then
export JAVA_HOME=`/usr/libexec/java_home -v $@`
fi
java -version
}
(originally suggested by Mark Beaty)
While this is a nice function, it suffers from a problem that it only affects JAVA_HOME - it does not help me in the case I have a Java tool that relies on finding "java" executable from PATH (such as Vert.x).
So I improved this script to also alter the PATH:
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
echo JAVA_HOME set to $JAVA_HOME
java -version
}
function removeFromPath() {
export PATH=$(echo $PATH | sed -E -e "s;:$1;;" -e "s;$1:?;;")
}
Now, it works like a charm:
neeme@Neemes-MacBook-Pro:~$ java -version
java version "1.6.0_31"
Java(TM) SE Runtime Environment (build 1.6.0_31-b04-414-11M3626)
Java HotSpot(TM) 64-Bit Server VM (build 20.6-b01-414, mixed mode)
neeme@Neemes-MacBook-Pro:~$ setjdk 1.7
JAVA_HOME set to /Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Home
java version "1.7.0_04"
Java(TM) SE Runtime Environment (build 1.7.0_04-b20)
Java HotSpot(TM) 64-Bit Server VM (build 23.0-b21, mixed mode)
neeme@Neemes-MacBook-Pro:~$ echo $PATH
/Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Home/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/opt/play:/opt/vert.x/bin:/opt/local/bin:/opt/local/sbin
I hope someone else also finds it useful!