Я хочу установить OpenJDK Java на Mac OSX и заставить его работать вместе с другими JDK, поскольку это более новая версия. В настоящее время я загрузил tar.gz и поместил его на свой путь, но это сложно поддерживать.

Единственная другая установка, которую я обнаружил, которая выполняет больше действий автоматически, - это установка через Homebrew cask. Похоже, тоже только текущая версия:

brew cask info java


java: 13,33: 5b8a42f3905b406298b72d750b6919f6

Значит, я могу установить его оттуда, но что дальше? Я застрял только на новой версии?

Jayson Minard

Ответов: 11

Ответы (11)

Note: These solutions work for various versions of Java including Java 8 through Java 17 (the LTS version). This includes alternative JDK's from OpenJDK, Oracle, IBM, Azul, Amazon Correto, Graal and more. Easily work with Java 7, Java 8, Java 9, Java 10, Java 11, Java 12, Java 13, Java 14, Java 15, Java 16, and Java 17!

You have a few options for how to do the installation as well as manage JDK switching. Installation can be done by Homebrew, SDKMAN, asdf, Jabba, or a manual install. Switching can be done by JEnv, SDKMAN, asdf, Jabba or manually by setting JAVA_HOME. All of these are described below.

TL;DR - Preferred Methods of Installation

You can install Java using whatever method you prefer including SDKMAN, asdf, Homebrew, or a manual install of the tar.gz file. The advantage of a manual install is that the location of the JDK can be placed in a standardized location for Mac OSX.

However, there are easier options such as SDKMAN and asdf that also will install other important and common tools for the JVM. These two primary options are described here.

Installing and Switching versions with SDKMAN

SDKMAN is a bit different and handles both the install and the switching. SDKMAN also places the installed JDK's into its own directory tree, which is typically ~/.sdkman/candidates/java. SDKMAN allows setting a global default version, and a version specific to the current shell.

  1. Install SDKMAN from https://sdkman.io/install

  2. List the Java versions available to make sure you know the version ID

    sdk list java
  3. Install one of those versions, for example, Java 17:

    sdk install java 17-open 
  4. Make Java 17 the default version:

    sdk default java 17-open

    Or switch to 17 for the current terminal session:

    sdk use java 17-open

When you list available versions for installation using the list command, you will see a wide variety of distributions of Java:

sdk list java

And install additional versions, such as JDK 11 from Amazon:

sdk install java

SDKMAN can work with previously installed existing versions. Just do a local install giving your own version label and the location of the JDK:

sdk install java my-local-13 /Library/Java/JavaVirtualMachines/jdk-13.jdk/Contents/Home

And use it freely:

sdk use java my-local-13

SDKMAN will automatically manage your PATH and JAVA_HOME for you as you change versions. And as a note, it installs Java versions to ~/.sdkman/candidates/java/.

More information is available in the SDKMAN Usage Guide along with other SDK's it can install and manage.

Installing and Switching versions with "asdf"

asdf is a version manager that supports installing and managing most languages, frameworks, and developer/devops tools. It has language specific plugins including one for Java.

  1. First, install asdf via https://asdf-vm.com/guide/getting-started.html (read there to setup your shell correctly), or more simply:

    brew reinstall asdf

    and read the doc for setting up your shell correctly, but if you are using asdf from Homebrew with ZSH you can execute this command to finish setup:

    echo -e "\n. $(brew --prefix asdf)/libexec/asdf.sh" >> ${ZDOTDIR:-~}/.zshrc
  2. Then install the Java plugin via https://github.com/halcyon/asdf-java

    asdf plugin add java

    and read the doc for setting up your shell correctly before continuing. Basically it says to add the following to your ~/.zshrc file (assuming you are not using another shell):

    . ~/.asdf/plugins/java/set-java-home.zsh
  3. Now list Java versions:

    asdf list-all java
  4. Install your favorite flavor and version:

    asdf install java openjdk-17

    or install the latest:

    asdf install java latest

Other important commands are...

  • List your installed versions:

    asdf list java
  • Set a global Java version:

    asdf global java openjdk-17
  • Set a local Java version for a directory:

    asdf local java openjdk-17

It's that easy! asdf will automatically manage your PATH and JAVA_HOME for you as you change versions. As a note, asdf installs Java versions to ~/.asdf/installs/java.

There are other languages and plugins for asdf here from the repository page: https://github.com/asdf-vm/asdf-plugins

Other Methods of Installation

Install with Homebrew

The version of Java available in Homebrew Cask previous to October 3, 2018 was indeed the Oracle JVM. Now, however, it has now been updated to OpenJDK. Be sure to update Homebrew and then you will see the lastest version available for install.

  1. install Homebrew if you haven't already. Make sure it is updated:

     brew update
  2. Add the casks tap:

     brew tap homebrew/cask-versions

    These casks change their Java versions often, and there might be other taps out there with additional Java versions.

  3. Look for installable versions:

     brew search java  

    or for Eclipse Temurin versions:

     brew search temurin     
  4. Check the details on the version that will be installed:

     brew info java

    or for the Temurin version:

     brew info temurin
  5. Install a specific version of the JDK such as java11, temurin8, temurin11, or just java or temurin for the most current of that distribution. For example:

     brew install java
     brew install --cask temurin

And these will be installed into /Library/Java/JavaVirtualMachines/ which is the traditional location expected on Mac OSX. There might be additional steps to make the JDK active reported at the end of the install process.

Install manually from OpenJDK download page:

If you need any and every version of Java, this is a good place to look.

  1. Download OpenJDK for Mac OSX from http://jdk.java.net/ (for example Java 17)

  2. Unarchive the OpenJDK tar, and place the resulting folder (i.e. jdk-17.jdk) into your /Library/Java/JavaVirtualMachines/ folder since this is the standard and expected location of JDK installs. You can also install anywhere you want in reality.

  3. Set JAVA_HOME environment variable to point at direction where you unarchived the JDK.

For further information see the answer specific to manual installation. Also see the section below "Switching versions manually" for more information on how to manage multiple manual installations.

Other installation options:

Some other flavours of OpenJDK are:

Azul Systems Java Zulu certified builds of OpenJDK can be installed by following the instructions on their site.

Zulu® is a certified build of OpenJDK that is fully compliant with the Java SE standard. Zulu is 100% open source and freely downloadable. Now Java developers, system administrators, and end-users can enjoy the full benefits of open source Java with deployment flexibility and control over upgrade timing.

Amazon Correto OpenJDK builds have an easy to use an installation package for Java 8, Java 11, Java 15, Java 16, and Java 17. It installs to the standard /Library/Java/JavaVirtualMachines/ directory on Mac OSX.

Amazon Corretto is a no-cost, multiplatform, production-ready distribution of the Open Java Development Kit (OpenJDK). Corretto comes with long-term support that will include performance enhancements and security fixes. Amazon runs Corretto internally on thousands of production services and Corretto is certified as compatible with the Java SE standard. With Corretto, you can develop and run Java applications on popular operating systems, including Linux, Windows, and macOS.

Where is my JDK?!?!

To find locations of previously installed Java JDK's installed at the default system locations, use:

/usr/libexec/java_home -V

Matching Java Virtual Machines (10):
17 (x86_64) "Homebrew" - "OpenJDK 17" /usr/local/Cellar/openjdk/17/libexec/openjdk.jdk/Contents/Home
11, x86_64: "Java SE 11" /Library/Java/JavaVirtualMachines/jdk-11.jdk/Contents/Home
1.8.301.09 (x86_64) "Oracle Corporation" - "Java" /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home /usr/local/Cellar/openjdk/17/libexec/openjdk.jdk/Contents/Home

You can also report just the location of a specific Java version using -v. For example for Java 17:

/usr/libexec/java_home -v 17


Knowing the location of the installed JDK's is also useful when using tools like JEnv, or adding a local install manually to SDKMAN, or linking a system JDK in Jabba -- and you need to know where to find them.

If you need to find JDK's installed by other tools, check these locations:

  • SDKMAN installs to ~/.sdkman/candidates/java/
  • asdf install to ~/.asdf/installs/java
  • Jabba installs to ~/.jabba/jdk

Version Switching

If you are using SDKMAN or asdf you are already covered and can stop reading! Otherwise, here are some options to switch existing VM installations.

Switching versions manually

The Java executable is a wrapper that will use whatever JDK is configured in JAVA_HOME, so you can change that to also change which JDK is in use.

For example, if you installed or untar'd JDK 16 to /Library/Java/JavaVirtualMachines/jdk-16.jdk if it is the highest version number it should already be the default, if not you could simply set:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-16.jdk/Contents/Home

And now whatever Java executable is in the path will see this and use the correct JDK.

A simple way to change JDKs is to create a function in your ~/.bashrc or ~/.zshrc file:

jdk() {
    export JAVA_HOME=$(/usr/libexec/java_home -v"$version");
    java -version

And then change JDKs simply by:

jdk 1.8
jdk 9
jdk 11
jdk 13

Switching versions with JEnv

JEnv expects the Java JDK's to already exist on the machine and can be in any location. Typically you will find installed Java JDK's in /Library/Java/JavaVirtualMachines/. JEnv allows setting the global version of Java, one for the current shell, and a per-directory local version which is handy when some projects require different versions than others.

  1. Install JEnv if you haven't already, instructions on the site http://www.jenv.be/ for manual install or using Homebrew.

  2. Add any Java version to JEnv (adjust the directory if you placed this elsewhere):

    jenv add /usr/local/Cellar/openjdk/17/libexec/openjdk.jdk/Contents/Home
  3. Set your global version using this command:

    jenv global 17

You can also add other existing versions using jenv add in a similar manner, and list those that are available. For example Java 8:

jenv add /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home 
jenv versions

See the JEnv docs for more commands. You may now switch between any Java versions (Oracle, OpenJDK, other) at any time either for the whole system, for shells, or per local directory.

To help manage JAVA_HOME while using JEnv you can add the export plugin to do this for you.

$ jenv enable-plugin export
  You may restart your session to activate jenv export plugin echo export plugin activated

The export plugin may not adjust JAVA_HOME if it is already set, so you may need to clear this variable in your profile so that it can be managed by JEnv.

You can also use jenv exec to run single commands with JAVA_HOME and PATH set correctly for that one command, which could include opening another shell.

Installing and Switching versions with Jabba

Jabba also handles both the install and the switching. Jabba also places the installed JDK's into its own directory tree, which is typically ~/.jabba/jdk.

  1. Install Jabba by following the instructions on the home page.

  2. List available JDK's

    jabba ls-remote
  3. Install Java JDK 12

    jabba install openjdk@1.12.0
  4. Use it:

    jabba use openjdk@1.12.0

You can also alias version names, link to existing JDK's already installed, and find a mix of interesting JDK's such as GraalVM, Adopt JDK, IBM JDK, and more. The complete usage guide is available on the home page as well.

Jabba will automatically manage your PATH and JAVA_HOME for you as you change versions.

Этот ответ расширяет превосходный ответ Джейсона с некоторыми более самоуверенными рекомендациями по лучшему подходу для вашего варианта использования:

  • SDKMAN - лучшее решение для большинства пользователей. Он прост в использовании, не имеет странной конфигурации и упрощает управление несколькими версиями для множества других проектов экосистемы Java.
  • Загрузка версий Java через Homebrew и переключение версий через jenv - хороший вариант, но требует дополнительной работы. Например, команды Homebrew в этом ответе, получившем большое количество голосов, больше не работают. jenv немного сложнее настроить, плагины плохо документированы, а в README говорится, что проект ищет нового сопровождающего. jenv по-прежнему отличный проект, он решает эту задачу, и сообщество должно быть благодарно за этот замечательный вклад. SDKMAN - лучший вариант, потому что он такой классный.
  • Написано Jabba - это многоплатформенное решение, обеспечивающее одинаковый интерфейс на Mac, Windows и ПК (он написан на Go, и это позволяет ему быть мультиплатформенным). Если вас интересует мультиплатформенное решение, это огромный аргумент. Если вас интересует только запуск нескольких версий на вашем Mac, вам не нужно многоплатформенное решение. Поддержка SDKMAN десятков популярных SDK - это то, чего вы упускаете, если используете Jabba.

Управление версиями вручную, наверное, худший вариант. Если вы решили вручную переключать версии, вы можете использовать этот код Bash вместо подробного кода Джейсона (фрагмент кода из homebrew-openjdk README:

jdk() {
        export JAVA_HOME=$(/usr/libexec/java_home -v"$version");
        java -version

Ответ Джейсона предоставляет основные команды для SDKMAN и jenv. Вот дополнительная информация о SDKMAN и дополнительная информация о jenv, если вам нужна дополнительная информация об этих инструментах.

Другой альтернативой является использование SDKMAN! См. https://wimdeblauwe.wordpress.com/2018/09/26/switching-between-jdk-8-and-11-using-sdkman/

Сначала установите SDKMAN: https://sdkman.io/install, а затем ...

  1. Установите Oracle JDK 8 с помощью: sdk install java 8.0.181-oracle
  2. Установите OpenJDK 11 с помощью: sdk install java 11.0.0-open

Для переключения:

  • Переключитесь на JDK 8 с sdk, используйте java 8.0.181-oracle
  • Переключитесь на JDK 11 с sdk, используйте java 11.0.0-open

Для установки по умолчанию:

  • По умолчанию JDK 8 с sdk по умолчанию java 8.0.181-oracle
  • По умолчанию для JDK 11 с sdk по умолчанию java 11.0.0-open

С Homebrew и jenv:

Предположение: компьютер Mac, и вы уже установили homebrew.

Установите Java с официального сайта Oracle. Вы можете установить несколько версий JDK. Он будет установлен по следующему пути:


Без jenvсистема будет использовать последнюю установленную java.

Если вы хотите использовать / управлять несколькими версиями, вы можете использовать jenv:

Установить и настроить jenv:

$ brew install jenv
$ echo 'export PATH="$HOME/.jenv/bin:$PATH"' >> ~/.zshrc
$ echo 'eval "$(jenv init -)"' >> ~/.zshrc
$ source ~/.zshrc

Добавить установленную java в jenv:

$ jenv add /Library/Java/JavaVirtualMachines/jdk1.8.0_202.jdk/Contents/Home
$ jenv add /Library/Java/JavaVirtualMachines/14.0.2.jdk/Contents/Home

Чтобы увидеть всю установленную java:

$ jenv versions

Команда выше выдаст список установленных java:

* (set by /Users/lpatel/.jenv/version)

Настройте версию Java, которую вы хотите использовать:

$ jenv global

IMHO, There is no need to install all the additional applications/packages.

Check available versions using the command:

> /usr/libexec/java_home -V
Matching Java Virtual Machines (8):
    11, x86_64: "Java SE 11-ea" /Library/Java/JavaVirtualMachines/jdk-11.jdk/Contents/Home
    10.0.2, x86_64: "Java SE 10.0.2"    /Library/Java/JavaVirtualMachines/jdk-10.0.2.jdk/Contents/Home
    9.0.1, x86_64:  "Java SE 9.0.1" /Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk/Contents/Home
    1.8.0_181-zulu-, x86_64:    "Zulu 8"    /Library/Java/JavaVirtualMachines/zulu-8.jdk/Contents/Home
    1.8.0_151, x86_64:  "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_151.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

Now if you want to pick Azul JDK 8 in the above list, and NOT Oracle's Java SE 8, invoke the command as below:

> /usr/libexec/java_home -v 1.8.0_181

To pick Oracle's Java SE 8 you would invoke the command:

> /usr/libexec/java_home -v 1.8.0_151

As you can see the version number provided shall be the unique set of strings: 1.8.0_181 vs 1.8.0_151

Manually switching system-default version without 3rd party tools:

As detailed in this older answer, on macOS /usr/bin/java is a wrapper tool that will use Java version pointed by JAVA_HOME or if that variable is not set will look for Java installations under /Library/Java/JavaVirtualMachines/ and will use the one with highest version. It determines versions by looking at Contents/Info.plist under each package.

Armed with this knowledge you can:

  • control which version the system will use by renaming Info.plist in versions you don't want to use as default (that file is not used by the actual Java runtime itself).
  • control which version to use for specific tasks by setting $JAVA_HOME

I've just verified this is still true with OpenJDK & Mojave.

On a brand new system, there is no Java version installed:

$ java -version
No Java runtime present, requesting install.

Cancel this, download OpenJDK 11 & 12ea on https://jdk.java.net ; install OpenJDK11:

$ cd /Library/Java/JavaVirtualMachines/
$ sudo tar xzf ~/Downloads/openjdk-11.0.1_osx-x64_bin.tar.gz

System java is now 11:

$ java -version
openjdk version "11.0.1" 2018-10-16

Install OpenJDK12 (early access at the moment):

$ sudo tar xzf ~/Downloads/openjdk-12-ea+17_osx-x64_bin.tar.gz 

System java is now 12:

$ java -version
openjdk version "12-ea" 2019-03-19

Now let's "hide" OpenJDK 12 from system java wrapper:

$ cd jdk-12.jdk/Contents/
$ sudo mv Info.plist Info.plist.disabled

System java is back to 11:

$ java -version
openjdk version "11.0.1" 2018-10-16

And you can still use version 12 punctually by manually setting JAVA_HOME:

$ export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-12.jdk/Contents/Home
$ java -version
openjdk version "12-ea" 2019-03-19

Вы можете использовать asdf для установки и переключения между несколькими версиями java. Также есть плагины для других языков. Вы можете установить asdf с помощью Homebrew

brew install asdf

Когда настроен asdf, установить java-плагин

asdf plugin-add java

Выберите версию для установки

asdf list-all java

Например, для установки и настройки accepttopenjdk8

asdf install java adoptopenjdk-8.0.272+10
asdf global java adoptopenjdk-8.0.272+10

И, наконец, если необходимо, настройте JAVA_HOME для вашей оболочки. Просто добавьте в свою оболочку сценарий инициализации, например ~ / .zshrc в случае zsh:

. ~/.asdf/plugins/java/set-java-home.zsh

Если на вашем компьютере установлено несколько версий, добавьте в профиль bash следующее:

экспорт JAVA_HOME_7 = $ (/ usr / libexec / java_home -v1.7)

экспорт JAVA_HOME_8 = $ (/ usr / libexec / java_home -v1.8)

экспорт JAVA_HOME_9 = $ (/ usr / libexec / java_home -v9)

И добавьте следующие псевдонимы:

псевдоним java7 = 'экспорт JAVA_HOME = $ JAVA_HOME_7'

псевдоним java8 = 'экспорт JAVA_HOME = $ JAVA_HOME_8'

псевдоним java9 = 'экспорт JAVA_HOME = $ JAVA_HOME_9'

И можете перейти на нужную версию, используя псевдоним:

В терминале:

~ >> java7 экспорт JAVA_HOME = $ JAVA_7_HOME

Вот как я это сделал.

Шаг 1: Установите Java 11

Вы можете скачать Java 11 dmg для Mac отсюда: https://www.oracle.com/technetwork/java/javase/downloads/jdk11-downloads-5066655.html

Шаг 2: После установки Java 11. Подтвердите установку всех версий. Введите в терминале следующую команду.

/usr/libexec/java_home -V

Шаг 3: Редактировать .bash_profile

sudo nano ~/.bash_profile

Шаг 4: Добавьте 11.0.1 по умолчанию. (Добавьте строку ниже в файл bash_profile).

export JAVA_HOME=$(/usr/libexec/java_home -v 11.0.1)

для перехода на любую версию

export JAVA_HOME=$(/usr/libexec/java_home -v X.X.X)

Теперь нажмите CTRL + X, чтобы выйти из bash. Нажмите «Y», чтобы сохранить изменения.

Шаг 5: Перезагрузить bash_profile

source ~/.bash_profile

Шаг 6: Подтвердите текущую версию Java

java -version

Чтобы оставаться с конкретным основным выпуском, активируйте кран AdoptOpenJDK с краном для варки, а затем установите желаемую версию с помощью установки brew cask install:

$ brew tap AdoptOpenJDK/openjdk
$ brew cask install 

Чтобы установить AdoptOpenJDK 14 с HotSpot, запустите:

$ brew tap AdoptOpenJDK/openjdk
$ brew cask install adoptopenjdk14

Вы можете установить версию JDK как хотите.

  • Домашнее пиво
  • SDK человек
  • Вручную

Затем я рекомендую использовать JENV для переключения между различными версиями и использовать JDK, который вам нужен глобально или локально.

Вы можете найти более подробную информацию о том, как установить и использовать JENV здесь -> https://blog.adamgamboa.dev/2021/06/17/using-jenv-to-switch-jkd-versions/

2022 WebDevInsider