【发布时间】:2020-05-16 20:02:58
【问题描述】:
根据文档,方法参考绝对不是静态调用。它适用于静态和非静态方法。 当我们在给定类中定义自己的非静态方法并尝试使用方法引用使用它时,编译时错误“无法对非静态方法进行静态引用”在 Function 的情况下不可见,而仅在情况下可见供应商、消费者和谓词。为什么会这样?
class Demo{
private Function<Student, Integer> p= Student::getGradeLevel; // fine
private Supplier<Integer> s = Student::supply; // compile-time error
private Predicate<Integer> p1= Student::check; //compile-time error
private Consumer<Integer> c= Student::consume; / compile-time error
private Function<String, String> f1 = String::toUpperCase; //fine
}
class Student{
public int getGradeLevel() {
return gradeLevel;
}
public boolean check(int i) {
return true;
}
public int supply() {
return 1;
}
public void consume(int i) {
System.out.println(i);
}
}
【问题讨论】:
-
我建议您访问official documentation about types of method references。第一行代码之所以编译,是因为它可以表示
student -> student.getGradeLevel等Student类型的实例方法。与使用Function相关时,这很容易理解,因为那是您使用p.apply(<the arbitrary object>)的时候。
标签: java lambda java-8 method-reference functional-interface