Tuesday, November 25, 2014

Easily changing java versions in OSX

In OSX, they've frankly done a pretty good job of enabling multiple versions of java at the same time, but just as frankly it's somewhat obscure and inconvenient to manage multiple versions. It's not mind bogglingly difficult but for us oldsters who are lazy, I created a convenient way to switch versions inspired by (though nowhere nearly as awesome as) rvm for ruby.

  1. Download all of the versions of java you want to use from the appropriate location java 1.6, java 7, or java 8. (you need at least one to start with)
  2. Add the following lines to ~/.bash_profile
  3. jvm() {
     export JAVA_HOME=`/usr/libexec/java_home -v "$1"`
     java -version
    }
    
    
  4. Either source .bash_profile by typing ". ~/.bash_profile" or simply close your terminal and relaunch

At this point you can change versions of java by typing:

jvm 1.6*
or
jvm 1.7*

Yes, there's more to it, refer to java_home for more version matching options, and it could be way more awesome, but this should be a quick help for those who just need a simple way to switch when troubleshooting/testing jvm version issues and you want to quickly change JDKs in an automated fashion. Note, this also works with fix pack and minor versions, you just need to refer to the version pattern matching of the '-v' option for java_home to know how to use it.

edit - I originally had an alias pointing to a function until a gracious commenter pointedly asked why I did it that way. Not having an answer I eliminated the alias. This shows the strength of my convictions about the "right way" to do things...