Working with different projects, each one having different JDK version requirements (mainly 1.8 and 17), with people contributing from different operating systems; it has been decided to use the JAVA_HOME
environment variable within our gradle
scripts to get the JDK path.
It works well, though one needs to export JAVA_HOME
to a different value, that differs for each individual contributor, each time one switches to another project.
I searched here at Stack sites, the SdkMan project and this blog post https://opensource.com/article/22/3/find-java-home about this topic.
The proposed solutions introduces much complexity to determine system type, locate available JDKs.
I ended-up writing my own implementation to find the JAVA_HOME
of a specific JDK version, although it only supports RedHat and Debian based Linux distributions.
Is there a standard method to determine the JAVA_HOME
, for a specific JDK version, in a fully system-agnostic way; be it Linux, BSD/MacOS, Windows?
Here is the shell script I wrote, only for Debian/RedHat based systems.
java_home
:
#!/bin/sh
# Usage:
# java_home [JDK_VERSION]
get_home() {
# get java_home from javac path
printf %s\\n "${1%/bin/javac}"
}
query_javac() {
{
command "$__ALTERNATIVES" --query javac || return 1
} | awk -v t="$1" \
'BEGIN{p="^" toupper( substr( t, 1, 1 ) ) substr( t, 2 ) ":"}$0~p{print $2}'
}
# find the alternatives command for this system
for cmd in update-alternatives alternatives false; do
__ALTERNATIVES=$(command -v "$cmd") && break
done
# If no version provided, return the home of the Best java version
java_home=$(
if [ $# -eq 0 ]; then
get_home "$(query_javac best)"
else
# Iterate the Alternative java versions
query_javac alternative |
while read -r javac; do
# Read the version string returned by the javac command
raw_javac_version=$(command "$javac" -version 2>&1)
case $raw_javac_version in
javac\ $1*)
# Print the home of this javac version and exit
get_home "$javac"
exit
;;
esac
done
fi
)
if [ -n "$java_home" ]; then
printf %s\\n "$java_home"
else
exit 1
fi
Example usage:
$ java_home 1.8
/usr/lib/jvm/java-8-openjdk-amd64
I am seeking a lighter, more standard, and more agnostic method of determining the Java home of specific JDK version.