Error in compilation of code with lambda expressio

2020-03-19 02:57发布

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:

\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.

2条回答
你好瞎i
2楼-- · 2020-03-19 03:13

Let me elaborate above answer further. Put the plugin given in above answer between <project> and </project> as below.

<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>
查看更多
我想做一个坏孩纸
3楼-- · 2020-03-19 03:28

By default, the maven-compiler-plugin uses Java 5 to compile the classes. 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. 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.

You need to configure it to use Java 8, like this:

<plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.3</version>
    <configuration>
      <source>1.8</source>
      <target>1.8</target>
    </configuration>
</plugin>
查看更多
登录 后发表回答