Problem:
Suppose we are building an application from scratch based on Maven and JDK 11 and our pom.xml file contains nothing but groupId/artifactId/version information. An attempt to compile will end with an error as in the title.
The same thing will happen if we have an application in Java 1.5 (yes, it happens...) and we try to upgrade JDK version to e.g. 1.8 or 11. Changing Java version in the project and trying to compile will also end with this error.
Requirements:
- installed IntelliJ, JDK and Maven as described here. We need Java 11 to be installed.
Solution:
Let's try to repeat this mistake by creating simple "Hello World" application wchich is based on Maven and uses JDK 11 from Amazon:
Tip: if you're wondering why I have such nice colors in the terminal, let me remind you that I set up the Idea terminal to use Git Bash underneath (described here). However when You use standard Windows Terminal (cmd.exe) or Windows PowerShell as a Terminal underneath colors also work.
- Maven uses "maven-compiler-plugin" to do the job, even if we don't have this plugin explicitly written into pom.xml
- this plugin (3.1.0) by default tries to set source and target bytecode version to 1.5 even if we set our project to use JDK 11:
- change the plugin version to a newer one - just add the plugin into the pom.xml explicitly
- set the source and target to 11 in the pom.xml.
Why explicitly set version to 11? Because without explicitly setting them, newer plugin (from 3.6.0) will use 1.6 as default. Compilation is OK now but language level is set to 1.6 even we can use 11 as our JDK:
So, to set up everything together (plugin and language) just put those in pom.xml:
You can also put information about source and target language directly into the plugin instead of defining properties:<properties><maven.compiler.source>11</maven.compiler.source><maven.compiler.target>11</maven.compiler.target></properties><build><pluginManagement><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.8.1</version></plugin></plugins></pluginManagement></build>
From JDK 1.9 and above plugin can also be configured using <release> option:<build><pluginManagement><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.8.1</version><configuration><source>11</source><target>11</target></configuration></plugin></plugins></pluginManagement></build>
Fortunately, when you create a new maven-based project from scratch in Idea, it (based on the selected JDK) automatically places the appropriate source and target for the language level in pom.xml (using <properties>).<build><pluginManagement><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.8.1</version><configuration><release>11</release></configuration></plugin></plugins></pluginManagement></build>