Set an alias in .zshrc etc. that sets the environment variables JAVA_HOME and PATH. Set for each installed Java Virtual Machine (JVM).
# AdoptOpenJDK 8
alias setjava8="export JAVA_HOME=/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home; export PATH=/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home/bin:$(echo ${PATH})"
# AdoptOpenJDK 11
alias setjava11="export JAVA_HOME=/Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home; export PATH=/Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home/bin:$(echo ${PATH})"
# AdoptOpenJDK 14
alias setjava14="export JAVA_HOME=/Library/Java/JavaVirtualMachines/adoptopenjdk-14.jdk/Contents/Home; export PATH=/Library/Java/JavaVirtualMachines/adoptopenjdk-14.jdk/Contents/Home/bin:$(echo ${PATH})"
# Amazon Corretto 8
alias setcorretto8="export JAVA_HOME=/Library/Java/JavaVirtualMachines/amazon-corretto-8.jdk/Contents/Home; export PATH=/Library/Java/JavaVirtualMachines/amazon-corretto-8.jdk/Contents/Home/bin:$(echo ${PATH})"
# Zulu OpenJDK 13
alias setzulu13="export JAVA_HOME=/Library/Java/JavaVirtualMachines/zulu-13.jdk/Contents/Home; export PATH=/Library/Java/JavaVirtualMachines/zulu-13.jdk/Contents/Home/bin:$(echo ${PATH})"
You can switch the Java version by entering the set alias name.
$ setjava14
Check the environment variables and java -version to see if they are switched.
$ echo; echo JAVA_HOME=${JAVA_HOME}; echo; echo PATH=${PATH}; echo; echo 'java -version'; java -version
JAVA_HOME=/Library/Java/JavaVirtualMachines/adoptopenjdk-14.jdk/Contents/Home
PATH=/Library/Java/JavaVirtualMachines/adoptopenjdk-14.jdk/Contents/Home/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin
java -version
openjdk version "14.0.2" 2020-07-14
OpenJDK Runtime Environment AdoptOpenJDK (build 14.0.2+12)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 14.0.2+12, mixed mode, sharing)
--Since the environment variable PATH is expanded when the alias is set, the length of the PATH set by the alias may increase each time the shell is started.
Recommended Posts