If you are dealing with multiple projects needing different Java versions to build, there is no need to set a new JAVA_HOME
environment variable value for each build. Instead execute Maven like:
JAVA_HOME=/path/to/your/jdk mvn clean install
It will build using the specified JDK, but it won't change your environment variable.
Demo:
$ mvn -v
Apache Maven 3.6.0
Maven home: /usr/share/maven
Java version: 11.0.6, vendor: Ubuntu, runtime: /usr/lib/jvm/java-11-openjdk-amd64
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.15.0-72-generic", arch: "amd64", family: "unix"
$ JAVA_HOME=/opt/jdk1.8.0_201 mvn -v
Apache Maven 3.6.0
Maven home: /usr/share/maven
Java version: 1.8.0_201, vendor: Oracle Corporation, runtime: /opt/jdk1.8.0_201/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.15.0-72-generic", arch: "amd64", family: "unix"
$ export | grep JAVA_HOME
declare -x JAVA_HOME="/usr/lib/jvm/java-11-openjdk-amd64"