简体   繁体   English

使用lambda表达式编译代码时出错

[英]Error in compilation of code with lambda expression

I have the following code: 我有以下代码:

package com.mongoDB;

import spark.Spark;

public class HelloWorldSparkStyle {
   public static void main(String[] args) {
       Spark.get("/hello", (req, res) -> "Hello World");
   }
}

It runs fine when I run it through main method but throws the following error when I try to compile it: 当我通过main方法运行它时,它运行良好,但是当我尝试对其进行编译时,抛出以下错误:

\HelloWorldSparkStyle.java:[9,33] error: lambda expressions are not supported in -source 1.5

D:\WorkspaceWithJava8\BeginnerProject>javac -version
javac 1.8.0_60

I am using Eclipse IDE and trying to compile it through command line. 我正在使用Eclipse IDE并尝试通过命令行进行编译。

By default, the maven-compiler-plugin uses Java 5 to compile the classes. 默认情况下, maven-compiler-plugin使用Java 5来编译类。 Quoting its documentation : 引用其文档

Also note that at present the default source setting is 1.5 and the default target setting is 1.5, independently of the JDK you run Maven with. 还要注意,当前的默认源设置是1.5,默认目标设置是1.5,与运行Maven的JDK无关。 If you want to change these defaults, you should set source and target as described in Setting the -source and -target of the Java Compiler. 如果要更改这些默认值,则应按照设置Java编译器的-source和-target中所述设置源和目标。

You need to configure it to use Java 8, like this: 您需要将其配置为使用Java 8,如下所示:

<plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.3</version>
    <configuration>
      <source>1.8</source>
      <target>1.8</target>
    </configuration>
</plugin>

Let me elaborate above answer further. 让我进一步阐述以上答案。 Put the plugin given in above answer between <project> and </project> as below. 将上面答案中给出的插件放​​在<project></project> ,如下所示。

<build>
<plugins>
    <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.3</version>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
        </configuration>
    </plugin>
</plugins>
</build>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM