下面將會教你如何在Terminal下,切換Java的版本。

Install Java

1
2
brew tap caskroom/versions
brew cask install java java6 java8

Check your Java version

1
2
ls /Library/Java/JavaVirtualMachines/
> 1.6.0.jdk jdk1.7.0_80.jdk jdk1.8.0_202.jdk openjdk-12.jdk

Check version details

1
2
3
4
5
6
7
/usr/libexec/java_home -V
> Matching Java Virtual Machines (5):
> 12, x86_64: "OpenJDK 12" /Library/Java/JavaVirtualMachines/openjdk-12.jdk/Contents/Home
> 1.8.0_202, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_202.jdk/Contents/Home
> 1.7.0_80, x86_64: "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_80.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

Setting ~/.zshrc

1
2
3
4
5
6
7
8
9
10
11
12
export JAVA_6_HOME=$(/usr/libexec/java_home -v1.6)
export JAVA_7_HOME=$(/usr/libexec/java_home -v1.7)
export JAVA_8_HOME=$(/usr/libexec/java_home -v1.8)
export JAVA_12_HOME=$(/usr/libexec/java_home -v12)

alias java6='export JAVA_HOME=$JAVA_6_HOME'
alias java7='export JAVA_HOME=$JAVA_7_HOME'
alias java8='export JAVA_HOME=$JAVA_8_HOME'
alias java12='export JAVA_HOME=$JAVA_12_HOME'

# default to Java12
java12

Magic time

1
2
3
4
5
6
7
8
9
10
11
java6
java -version

java7
java -version

java8
java -version

java12
java -version

References

  1. Mac 環境設定