Eclipse Maven 和 Java 8 问题

Dor*_*oro 2 java eclipse maven java-8

我从简单的 Web 应用程序迁移到 Maven Web 应用程序,并使用 Eclipse Neon 遇到了一个令人沮丧的问题:在 pom.xml 中添加使用 Java 8 或 7 的规范后,它不起作用。

为了验证它是否有效,我编写了一个简单的类,在其中使用了 try(表达式) 声明。

我应该怎么做才能在 Maven 中使用 Java 8(我已经安装并且它可以在正常的 Web 应用程序中工作)?

pom.xml的代码是这样的:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.webdata</groupId>
  <artifactId>WebParser</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>WebParser</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

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

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

    <dependency>
          <groupId>net.sourceforge.htmlunit</groupId>
          <artifactId>htmlunit</artifactId>
          <version>2.23</version>
        </dependency>
  </dependencies>
</project>
Run Code Online (Sandbox Code Playgroud)

dav*_*xxx 5

首先,您JAVA_HOME必须指向 JDK 1.8。
否则,如果不是这种情况,您必须在编译器配置中指定 JDK 1.8 作为源和目标,pom.xml如下所示:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <source>1.8</source>
        <target>1.8</target>
        <compilerVersion>1.8</compilerVersion>      
        <fork>true</fork>
        <executable>D:\jdk1.8\bin\javac</executable>                
    </configuration>
</plugin>
Run Code Online (Sandbox Code Playgroud)

然后,在 Eclipse 中,您必须检查首选项:

  • Java->Installed JREs安装了 1.8 JRE/JDK。

如果您想将 1.8 用于 Eclipse 中任何新创建的项目,您可以将以下设置设置为默认值:

  • Java->Installed JREs:选择 1.8。
  • Java->Compiler:选择JDK编译器合规级别为1.8。

如果默认首选项不使用 1.8 编译合规性和 JDK/JRE,或者该项目是在此 Eclipse 外部创建的,并且首选项设置为 1.8 编译合规性和 JDK/JRE,则您应该检查并可能调整properties您的 Eclipse 项目
来执行此操作,进入项目的属性,然后Java Build Path进入Libraries选项卡。您必须检查是否JRE System Library使用 Java 1.8。如果不是,请更换1.8版本。
完成后,请始终在项目的属性中检查Java Compiler您使用的 JDK 编译器是否符合 Java 1.8。

它应该有效。