vim ~/.bash_profile 进入编辑模式加入如下代码,路径根据实际情况修改;
source ~/.bash_profile 保存更新;
通过java -version查看当前版本,终端直接输入jdk21切换jdk版本;
# JDK Config
JAVA_HOME_8=/Library/Java/JavaVirtualMachines/jdk-1.8.jdk/Contents/Home
JAVA_HOME_21=/Library/Java/JavaVirtualMachines/jdk-21.jdk/Contents/Home
# 默认使用 JDK 8
export JAVA_HOME=$JAVA_HOME_8
# 设置 CLASSPATH 和 PATH
CLASSPATH="$JAVA_HOME/lib/tools.jar:$JAVA_HOME/lib/dt.jar:."
PATH="$JAVA_HOME/bin:$PATH"
export PATH
export CLASSPATH
# 定义别名来切换 JDK 版本
alias jdk8='export JAVA_HOME=$JAVA_HOME_8; export CLASSPATH="$JAVA_HOME/lib/tools.jar:$JAVA_HOME/lib/dt.jar:."; export PATH="$JAVA_HOME/bin:$PATH"; echo "current JDK has switched to oracle jdk version 1.8."; java -version'
alias jdk21='export JAVA_HOME=$JAVA_HOME_21; export CLASSPATH="$JAVA_HOME/lib/tools.jar:$JAVA_HOME/lib/dt.jar:."; export PATH="$JAVA_HOME/bin:$PATH"; echo "current JDK has switched to openjdk version 21."; java -version'