Maven编译错误:(使用-source 7或更高版本启用菱形运算符)

Hap*_*ing 45 java intellij-idea maven-3 maven

我在IntelliJ,JDK1.8,maven 3.2.5中使用maven.编译错误:使用-source 7或更高版本启用钻石歌剧.详情如下:

  [ERROR] COMPILATION ERROR : 
  [INFO] -------------------------------------------------------------
  [ERROR] TrainingConstructor.java:[31,55] diamond operator is not supported in -source 1.5 (use -source 7 or higher to enable diamond operator)
  [ERROR] DTM.java:[79,21] try-with-resources is not supported in -source 1.5  (use -source 7 or higher to enable try-with-resources)
  [ERROR] ticons.java:[53,44] diamond operator is not supported in -source 1.5  (use -source 7 or higher to enable diamond operator)
Run Code Online (Sandbox Code Playgroud)

有什么建议?是否有其他配置来设置此-source级别?好像它不使用java 1.8.

Ser*_*auk 71

检查您maven-compiler-plugin的配置方式,它应该使用Java 7或更高版本:

<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>
    </configuration>
</plugin>
Run Code Online (Sandbox Code Playgroud)

有关更完整的答案,请参阅下面的答案.


Fab*_*nte 56

为什么会这样

问题出现是因为

[...]目前默认的源设置为1.5,默认目标设置为1.5,与您运行Maven的JDK无关.如果要更改这些默认值,则应设置源和目标,如设置Java编译器的-source和-target中所述.

Maven编译器插件简介

这就是改变JDK对源级别没有影响的原因.所以你有几种方法可以告诉Maven使用什么源代码.

解决方案

  • 在pom.xml中配置Maven编译器插件
<properties>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
Run Code Online (Sandbox Code Playgroud)
  • 或设置这些属性(始终在pom中)
<build>

<plugins>
    <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
            <source>1.7</source>
            <target>1.7</target>
        </configuration>
    </plugin>
</plugins>
...
Run Code Online (Sandbox Code Playgroud)

JDK VERSION使用?

如果您在此示例中设置目标1.7,请确保mvn命令实际上是使用jdk7(或更高版本)启动的

IDE上的语言水平

通常,IDE使用maven pom.xml文件作为项目配置的源.在IDE中更改编译器设置并不总是对maven构建有效.这就是为什么保持项目始终可以通过maven管理(并与其他IDE互操作)的最佳方法是编辑pom.xml文件并指示IDE与maven同步.


khm*_*ise 5

你必须改变你的配置:

<project>
  [...]
  <build>
    [...]
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.2</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
    [...]
  </build>
  [...]
</project>
Run Code Online (Sandbox Code Playgroud)

您应该了解source/tagetJavaC中的选项与JDK 1.8/1.7等的使用之间的区别.

除此之外,你应该升级使用maven-compiler-plugin.