Search code examples
javamavenjavac

Does maven compiler plugin with source 1.6 configuration recognise API introduced since 1.7?


I've a maven project with the maven-compiler-plugin configured as below:

    <plugin>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.0</version>
      <configuration>
        <source>1.6</source>
        <target>1.6</target>
      </configuration>
    </plugin>

In my code I use a class java.nio.charset.StandardCharsets which is introduced since 1.7. I'm surprised that my code compiles successfully, shouldn't the plugin throw an error because java.nio.charset.StandardCharsets is not 1.6 compilant?


Solution

  • Neither target nor source relate in any way to what classes are available on the compiler's classpath. If you're compiling your code with the 1.7 compiler then any classes that shipped with 1.7 will be available to your code.

    What target does is tell the compiler to output .class files in a format that is compatible with the 1.6 release of java. source says only accept java code that would compile with the 1.6 version of the compiler.

    So it's perfectly legitimate to make a call to a class that shipped only on 1.7 or later using Java 1.6 compatible source code written into a class file that is compatible with Java 1.6. It just won't run on 1.6.

    The only way to ensure your code will run on 1.6 (if that's what you're trying to do) is to use a 1.6 JDK to compile your project.