In this short post, I’d like to share with you guys how to change Java version for a Maven project. Simply declare the following properties in the pom.xml file:

<project>
	[...]

	<properties>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
	</properties>

	[...]
	
</project>
Then Maven will instruct Java compiler to compile source code against Java version 1.8, and generate .class files compatible with Java 1.8 as well. It’s equivalent to using the –source and –target flags of Java compiler (javac program).

Note that the source version must be equal to or less than the target version. Here’s another example:

<properties>
	<maven.compiler.source>1.8</maven.compiler.source>
	<maven.compiler.target>10</maven.compiler.target>
</properties>
This will generate the .class files compatible with Java 10, with source code compatible to Java 8.

Alternatively, you can also change Java version for a Maven project by configuring the Maven compiler plugin as follows:

<project>
	[...]

	<build>	
		<plugins>
		    <plugin>    
		        <artifactId>maven-compiler-plugin</artifactId>
		        <configuration>
		        	<source>11</source>
		        	<target>15</target>
		        </configuration>
		    </plugin>
		</plugins>
	</build>

	[...]
	
</project>
This tells Java compiler to compile source code against Java version 11, and generate the .class files according to Java 15 format. If you want to use the same Java version for both source and target, use the <release> tag like this:

<configuration>
    <release>13</release>
</configuration>
  

Change Java version for a multi-module Maven project:

In case you have a multi-module Maven project, the sub modules will inherit the compiler source and target settings from the parent project. But you can also override the settings in a specific module.

 

Change Java version for a Maven project in Eclipse:



In Eclipse, you have to update the project for the changes to take effect. Right click on the project, click Maven > Update Project.

 

Change Java version for a Maven project in NetBeans IDE:

NetBeans automatically updates the change right after you save the pom.xml file. So you don’t have to do anything.

 

Change Java version for a Maven project in IntelliJ IDEA:

With IntelliJ IDEA, you may have to reload the Maven project by clicking the Refresh button in Maven view. Or right click on the project, then select Maven > Reload project.

 


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment