2017/12/10

# Java 编译版本的坑

Maven中可以指定JDK，如下:

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>


Merely setting the target option does not guarantee that your code actually runs on a JRE with the specified version. The pitfall is unintended usage of APIs that only exist in later JREs which would make your code fail at runtime with a linkage error. To avoid this issue, you can either configure the compiler’s boot classpath to match the target JRE or use the Animal Sniffer Maven Plugin to verify your code doesn’t use unintended APIs. In the same way, setting the source option does not guarantee that your code actually compiles on a JDK with the specified version. To compile your code with a specific JDK version, different than the one used to launch Maven, refer to the Compile Using A Different JDK example.

## 正确的做法

<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<verbose>true</verbose>
<fork>true</fork>
<executable><!-- path-to-javac --></executable>
<compilerVersion>1.7</compilerVersion>
</configuration>
</plugin>
</plugins>


<profiles>
[...]
<profile>
<id>compiler</id>
<properties>
<JAVA_1.7_HOME><!-- somePath --></JAVA_1.7_HOME>
</properties>
</profile>
</profiles>