由于 Java 版本导致 mvn 编译错误

mvn compilation error due to Java version

在我的Ubuntu14.04系统中比较奇怪。我安装了 Oracle JDK 1.7。然后使用 mvn 编译项目。但是报错:

Apache Maven 3.0.5
Maven home: /usr/share/maven
Java version: 1.7.0_40, vendor: Oracle Corporation
Java home: /opt/pro/JDK/jdk1.7.0_40/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "3.13.0-43-generic", arch: "amd64", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/share/maven/conf/settings.xml
[DEBUG] Reading user settings from /home/shijiex/.m2/settings.xml
[DEBUG] Using local repository at /home/shijiex/.m2/repository
[DEBUG] Using manager EnhancedLocalRepositoryManager with priority 10 for /home/shij....
      ............
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.547s
[INFO] Finished at: Tue Jan 20 15:26:28 AST 2015
[INFO] Final Memory: 7M/155M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.0.2:compile (default-compile) on project org.bytecode.generation.sample: Compilation failure: Compilation failure:
[ERROR] /other/projectbase/workspace/org.bytecode.generation.sample/src/main/java/org/methodhandle/templates/TYPES.java:[3,7] error: enums are not supported in -source 1.3
[ERROR] 
[ERROR] (use -source 5 or higher to enable enums)
[ERROR] /other/projectbase/workspace/org.bytecode.generation.sample/src/main/java/org/methodhandle/templates/Templates.java:[7,19] error: generics are not supported in -source 1.3
[ERROR] 
[ERROR] (use -source 5 or higher to enable generics)
[ERROR] /other/projectbase/workspace/org.bytecode.generation.sample/src/main/java/org/methodhandle/templates/BaseTemplate.java:[11,9] error: variable-arity methods are not supported in -source 1.3
[ERROR] -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.0.2:compile (default-compile) on project org.bytecode.generation.sample: Compilation failure

此错误表明 JDK 是 1.7,但它仍在使用 1.3,因此无法识别变量参数、枚举等功能。

我是否缺少某些配置?

我没有设置 JAVA_HOME 环境变量。默认是 Oracle 1.7,maven 输出也显示它是 1.7。

XXX@shijie-ThinkPad-T410:/other/projectbase/workspace

/org.bytecode.generation.sample$ java -version 
java version "1.7.0_40"
Java(TM) SE Runtime Environment (build 1.7.0_40-b43)
Java HotSpot(TM) 64-Bit Server VM (build 24.0-b56, mixed mode)

您可以将类似这样的内容直接添加到您的 POM 中:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.2</version>
    <configuration>
        <source>${jdk.version}</source>
        <target>${jdk.version}</target>
    </configuration>
</plugin>

您可以在官方 Maven Compiler plugin 页面上找到更多信息