查看所有已安装版本

bennyrhysdeMacBook-Pro:~ bennyrhys$ /usr/libexec/java_home -V
Matching Java Virtual Machines (6):
12.0.1, x86_64: "Java SE 12.0.1" /Library/Java/JavaVirtualMachines/jdk-12.0.1.jdk/Contents/Home
12.0.1, x86_64: "OpenJDK 12.0.1" /Library/Java/JavaVirtualMachines/openjdk-12.0.1.jdk/Contents/Home
1.8.0_212, x86_64: "AdoptOpenJDK 8" /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home
1.8.0_121, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home
1.6.0_65-b14-468, x86_64: "Java SE 6" /Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
1.6.0_65-b14-468, i386: "Java SE 6" /Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home

/Library/Java/JavaVirtualMachines/jdk-12.0.1.jdk/Contents/Home

vim ~/.bash_profile添加以下内容:

export JAVA7_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_80.jdk/Contents/Home
export JAVA8_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_111.jdk/Contents/Home
export JAVA10_HOME=/Library/Java/JavaVirtualMachines/jdk-10.0.2.jdk/Contents/Home
#默认jdk
export JAVA_HOME=$JAVA8_HOME

修改.bash_aliases文件,增加以下内容(没有此文件就创建)

alias jdk7='export JAVA_HOME=$JAVA7_HOME'
alias jdk8='export JAVA_HOME=$JAVA8_HOME'
alias jdk10='export JAVA_HOME=$JAVA10_HOME'

命令行控制版本

bennyrhysdeMacBook-Pro:~ bennyrhys$ java -version
java version "12.0.1" 2019-04-16
Java(TM) SE Runtime Environment (build 12.0.1+12)
Java HotSpot(TM) 64-Bit Server VM (build 12.0.1+12, mixed mode, sharing)
bennyrhysdeMacBook-Pro:~ bennyrhys$ jdk8
bennyrhysdeMacBook-Pro:~ bennyrhys$ java -version
java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)
bennyrhysdeMacBook-Pro:~ bennyrhys$