---
title: "How to switch JDK version on Mac OS X"
author: "flashcloud"
date: "2015-12-23T15:31:03Z"
tags: []
categories: ["编程语言"]
slug: "how-to-switch-jdk-version-on-mac-os-x"
draft: false
lastmod: "2015-12-23T15:31:03Z"
id: 2265971
url: "https://flashcloud.iteye.com/blog/2265971"
---

[JAVA](http://www.jayway.com/tag/java/)

出自：[http://www.jayway.com/2014/01/15/how-to-switch-jdk-version-on-mac-os-x-maverick/](http://www.jayway.com/2014/01/15/how-to-switch-jdk-version-on-mac-os-x-maverick/)

Apple decided to remove the Java Preferences application in a software update and afterwards in has been difficult to change the JDK version on Mac OS X. I especially noticed this after I installed the JDK 8 early access preview which makes some of the tips that you find on various blogs online useless. After a lot of googling I finally found a simple solution that I’d like to share.

 

What you do is to edit your `~/.bash_profile` and add the following:

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

functionsetjdk(){

  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

}

functionremoveFromPath(){

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

}

setjdk1.7

What the script does is to first remove other JDK versions in the `PATH` so that they won’t interfere with our new JDK version. Then it makes some clever use of `/usr/libexec/java_home` which is a command that lists installed JDK versions. The `-v` argument tells `java_home` to return the path of the JDK with the supplied version, for example 1.7. We also update the `PATH` to point to the `bin` directory of the newly found `JAVA_HOME` directory. At the end we can simply execute the function using

 

1

setjdk1.7

which selects the latest installed JDK version of the 1.7 branch. To select a specific version you can simply execute

 

1

setjdk1.7.0\_51

 

instead. Run `/usr/libexec/java_home -h` to get more details on how to choose versions.

That’s it! All credits should go to [Neeme Praks](http://superuser.com/users/141239/neeme-praks) and his answer on [superuser.com](http://superuser.com/a/568016).