How to fix the "Unable to locate a Java Runtime" error on Xcode with Kotlin Multiplatform

A couple of days ago I opened my Kotlin Multiplatform pet project MoneyFlow on a different machine than usual. When I tried to run the app on the iOS simulator on Xcode, the build failed with a very strange error: “The operation couldn’t be completed. Unable to locate a Java Runtime”.

This was a very strange issue because the JDK is installed and everything is working on the command line and Android Studio/IntelliJ.

After doing some research, I found out in a comment of a Youtrack issue that Xcode is taking the JDK version from /usr/libexec/java_home. So I tried to run /usr/libexec/java_home in the command line and I got the same error: The operation couldn’t be completed. Unable to locate a Java Runtime. Still strange.

I usually install the JDK manually with Homebrew, but for this time I decided to give sdkman a try. And that was the problem because sdkman “doesn’t expose” the JDK version to /usr/libexec/java_home.

So I went back to the old and good manual way. Since the AdoptOpenJDK tap is deprecated, I tried the Temurin one and installed Java 11 and Java 8.

brew tap homebrew/cask-versions

brew install --cask temurin8

brew install --cask temurin11

Then I adapted a couple of alias (to add on .zshrc or .bash_profile file) that I found out in this article to help me switch easily between Java 11 and Java 8, whenever I need.

export JAVA_11_HOME=/Library/Java/JavaVirtualMachines/temurin-11.jdk/Contents/Home
export JAVA_8_HOME=/Library/Java/JavaVirtualMachines/temurin-8.jdk/Contents/Home

alias java11="export JAVA_HOME=$JAVA_11_HOME"
alias java8="export JAVA_HOME=$JAVA_8_HOME"

# Set default to Java 11
java11

And with the manual installation, the build started working again!


Another solution, suggested by Martin Bonnin is to explicitly set the JAVA_HOME inside the plist files under ~/Library/LaunchAgents/