使用Consumer对象的两种语法之间有什么区别?

时间:2018-09-22 19:22:40

标签: java lambda

我从tutorial中读取了以下代码,并使其在Eclipse中运行,一切都很好。

import java.util.Arrays; 
import java.util.List; 
import java.util.function.Consumer; 
/* w w w .j a va2s . c o m*/ 

public class Main{ 
    public static void main(String[] args) { 
    List<Student> students = Arrays.asList( new Student("John", 3), new Student("Mark", 4) );

    acceptAllEmployee(students, e -> System.out.println(e.name)); 
    acceptAllEmployee(students, e -> { e.gpa *= 1.5; }); 
    acceptAllEmployee(students, e -> System.out.println(e.name + ": " + e.gpa)); 
}

public static void acceptAllEmployee(List<Student> student, Consumer<Student> printer) { 
    for (Student e : student) { printer.accept(e); } } 
} 

class Student { public String name; public double gpa; Student(String name, double g) { 
    this.name = name; this.gpa = g; } 
}

然后我决定将这行代码添加到列表声明的下方:

Consumer c = (e) -> {System.out.println(e.name);};

令人惊讶的是,它会导致错误!

我无法弄清楚这段代码有什么问题,因为原始代码用lambda表达式编写e.name并没有问题,尽管e的类型仍然是未知的,但是在我的代码中这是一个问题!

错误:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
name cannot be resolved or is not a field
  at com.test.Main.main(ExamineCharsets.java:9)

谢谢。

1 个答案:

答案 0 :(得分:2)

您需要设置使用者参数的类型才能使用其字段:

Consumer<Student> c = (e) -> {System.out.println(e.name);};