Friday 5 December 2014

Switching between multiple JDKs on Mac OSX

Suppose you are working on a few Java projects and each of which needs a specific version of JDK.

First. make sure that you download your required JDKs: JDK 8 and JDK 7. gm


Second, look for .bash_profile in your home directory ~. If you can't find it, create it as follows:

touch ~/.bash_profile

Next, use a text editor such as vim to open this file as follows:

vim ~/.bash_profile

Now let's add some aliases that will allow us to easily switch between JDKs:

alias setJdk6='export JAVA_HOME=$(/usr/libexec/java_home -v 1.6)'
alias setJdk7='export JAVA_HOME=$(/usr/libexec/java_home -v 1.7)'
alias setJdk8='export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)'

/usr/libexec/java_home is just a command (symlink) that gives you the path for the active JDK, and using -v xx shows the path to the JDK with version xx.


After you added the above aliases to the .bash_profile file, save and close the file and run:

source ~/.bash_profile

This will set the aliases for you. Now to switch between the JDKs, just type setJdkX (replace X with the version number). Example:

setJdk8 

If you would like to know how you can prevent modification of a private field in java, see: Preventing modification of a private field in Java

No comments:

Post a Comment