Monday, 3 March 2014

How to fix Java Language Level Issues

When using other people's source code you might discover that you receive an error like.

"java: strings in switch are not supported in -source 1.6
(use -source 7 or higher to enable strings in switch)"

Or something similar.

Define Language Levels in the pom.xml

I tackle this in two ways. One for the command line and one for the IDE.

For the command line I add the source and target to the maven compiler plugin

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>

By default the maven compiler is set to Java 1.5

I tend to want to use features in 1.6 or 1.7, so I set it to 1.7

Having the above in your pom file should mean that when you import the project into your IDE it sets the language settings appropriately.

And should run properly when you run "mvn clean compile"

Adjust the Compiler Settings

In Settings we have the Compiler settings

  • File \ Settings \ Compiler \ Java Compiler
We might need to set these up to use the level we need.

Adjust the Project Settings

When running in the IDE we might need to change a few things

In IntelliJ you find the language settings in a few places.

Project level we can define the SDK and the Language Level.


  • File \ Project Structure | Project Settings \ Project 
We can override the SDK or set the Project Language Level

Staying on Project we want to check the Platform Settings

And that we have an SDK of the required version setup and in use.

Check Modules Settings as well

You might even need to check in the Module settings on the sources tab
  • File \ Project Structure | Project Settings \ Modules