Home > Blockchain >  How can Homebrew automatically update JAVA_HOME after it updates JDKs?
How can Homebrew automatically update JAVA_HOME after it updates JDKs?

Time:09-13

I'm using macOS, when homebrew updates the JDK I have to manually update the $JAVA_HOME path in .zshrc since it uses the version number in its path, just replace the version number to a newer one like

/usr/local/Cellar/openjdk@11/11.0.14/libexec/openjdk.jdk/Contents/Home

to

/usr/local/Cellar/openjdk@11/11.0.16/libexec/openjdk.jdk/Contents/Home

As you can see there is just a difference in version numbers, other directory names are still the same. Is there any way to automatically update JAVA_HOME to the path that Homebrew just updated?

CodePudding user response:

You can use the default macOS command java_home:

% /usr/libexec/java_home -v 11
/opt/homebrew/Cellar/openjdk@11/11.0.16.1/libexec/openjdk.jdk/Contents/Home

And put this in your .zshrc:

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

From man java_home:

java_home - return a value for $JAVA_HOME

CodePudding user response:

I eventually figured out what the problem is. I found a difference between openjdk@11 and adoptopenjdk11 installed with Homebrew.

The situation was I actually got 3 java paths on my mac, jre8, openjdk@11 and openjdk@8.

In my opinion, openjdk@{xx} is like unregistered binaries that are not bound with java_home (brew formulae), however, adoptopenjdk{xx} are more like registered ones(brew cask).

And what made this situation more complex is the jre8 downloaded from Download Java for macOS which pinned the java_home to

/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home

That is why I could not find any other JDK paths (other than the one I downloaded from the java official website) through executing

$ /usr/libexec/java_home -V

since it actually searches for and lists Java Virtual Machines which are included by JREs. This relates to a common confusion that new developers sometimes would have - the difference between JDK JRE and even JVM (What is the difference between JDK and JRE?).

So the solution is installing adoptopenjdk{xx} if you are not strictly sticking with openjdk@{xx}, it would register the path of its JRE-contained JVM to the variable java_home , and it's ready to go with export in the bash/zshell profile.

Thanks to @Ortomala Lokni and @g00se as they provide useful info that inspired me to look deeper into this.

  • Related