Last Updated: February 25, 2016
·
297
· paulcodes

How to hot-swap between java versions on a mac

If you are running multiple versions of java for different apps you can add this small function to your .bash_profile and you can then swap your java home per terminal window.

vi into your bash_profile or bashrc

$ vi ~/.bash_profile

Paste the following 2 methods into your bash_profile or bashrc

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
}

function removeFromPath() {
  export PATH=$(echo $PATH | sed -E -e "s;:$1;;" -e "s;$1:?;;")
}

Then below that set java 8 to be the default default

setjdk 1.8 

Whenever you want to swap your home to another version just call setjdk {java.version}