如何更改mac上的Java默认版本?


当前回答

将以下代码行添加到你的.zshrc(或bash_profile):

alias j='f(){export JAVA_HOME=/usr/libexec/ JAVA_HOME -v $1};f'

保存到会话:

$ source .zshrc

执行命令(例如j13, j14, j1.8…)

$ j 1.8

解释 这是参数化的,所以你不需要像其他解决方案一样更新脚本。如果您没有安装JVM,系统会告诉您。案例示例如下:

/Users/user/IDE/project $ j 1.8
/Users/user/IDE/project $ java -version
openjdk version "1.8.0_265"
OpenJDK Runtime Environment (AdoptOpenJDK)(build 1.8.0_265-b01)
OpenJDK 64-Bit Server VM (AdoptOpenJDK)(build 25.265-b01, mixed mode)
/Users/user/IDE/project $ j 13
/Users/user/IDE/project $ java -version
openjdk version "13.0.2" 2020-01-14
OpenJDK Runtime Environment (build 13.0.2+8)
OpenJDK 64-Bit Server VM (build 13.0.2+8, mixed mode, sharing)
/Users/user/IDE/project $ j 1.7
Unable to find any JVMs matching version "1.7".

其他回答

博士tl;

加一行:

出口JAVA_HOME = ' /图书馆/ Java / JavaVirtualMachines / jdk1.8.0_144.jdk /内容/家庭的

到文件

~ / . bash_profile

(取代jdk1.8.0_144。JDK的下载版本)

然后源~/.bash_profile

您可以将其添加到.bash_profile中,以设置默认版本。

//Open bash profile
open ~/.bash_profile

export JAVA_HOME=`/usr/libexec/java_home -v 1.8`

// run bash profile
source ~/.bash_profile

将此函数添加到bashrc或zshrc, java-change [version]以选择JDK

# set and change java versions
function java-change() {
  echo "----- old java version -----"
  java -version
  if [ $# -ne 0 ]; then
    export JAVA_HOME=`/usr/libexec/java_home -v $@`
    export PATH=$JAVA_HOME/bin:$PATH
  fi
  echo "----- new java version -----"
  java -version
}

来自Apple官方java_home(1)手册页:

**USAGE**

   /usr/libexec/java_home  helps  users  set a $JAVA_HOME in their login rc files, or provides a way for
   command-line Java tools to use the most appropriate JVM which can satisfy a minimum version or archi-
   tecture  requirement.  The --exec argument can invoke tools in the selected $JAVA_HOME/bin directory,
   which is useful for starting Java command-line tools from launchd plists without hardcoding the  full
   path to the Java command-line tool.

   Usage for bash-style shells:
          $ export JAVA_HOME=`/usr/libexec/java_home`

   Usage for csh-style shells:
          % setenv JAVA_HOME `/usr/libexec/java_home`

使用jenv是一种简单的方法。(2022年更新)

安装jenv:参见入门 使用brew安装java Brew install openjdk@11 Ln -s /usr/local/opt/openjdk@11/libexec/openjdk。jdk /图书馆/ Java / JavaVirtualMachines / openjdk - 11. jdk #其他java Brew install openjdk@8 Brew install openjdk@17 添加java到jenv jenv add /Library/Java/JavaVirtualMachines/openjdk-11.jdk/Contents/Home 用法:参考jenv