Java 使用方法参考了解编译时错误

Java 使用方法参考了解编译时错误,java,lambda,java-8,method-reference,functional-interface,Java,Lambda,Java 8,Method Reference,Functional Interface,根据文档,方法引用绝对不是静态调用。它对静态和非静态方法都有效。 当我们在给定类中定义自己的非静态方法并尝试使用方法引用时,编译时错误“无法对非静态方法进行静态引用”在函数中不可见,而仅在供应商、消费者和谓词中可见。为什么会这样 class Demo{ private Function<Student, Integer> p= Student::getGradeLevel; // fine private Supplier<Integer> s = Stu

根据文档,方法引用绝对不是静态调用。它对静态和非静态方法都有效。 当我们在给定类中定义自己的非静态方法并尝试使用方法引用时,编译时错误“无法对非静态方法进行静态引用”在函数中不可见,而仅在供应商、消费者和谓词中可见。为什么会这样

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);
    }
}
类演示{
私有函数p=Student::getGradeLevel;//很好
私有供应商s=Student::supply;//编译时错误
私有谓词p1=Student::check;//编译时错误
私有使用者c=Student::consume;/编译时错误
私有函数f1=String::toUpperCase;//很好
}
班级学生{
public int getGradeLevel(){
返回等级;
}
公共布尔检查(int i){
返回true;
}
公共供应{
返回1;
}
公共空间消耗(int i){
系统输出打印LN(i);
}
}

您必须遵循
Student
方法的返回类型和形式参数类型,并使用适当的功能界面


私人供应商s=Student::supply;//编译时错误

供应商
不消耗任何东西,返回
T
。例如:

Student student = new Student();
Supplier<Integer> s = () -> student.supply();

private谓词p1=Student::check//编译时错误

同样的问题,但是
谓词
消耗
T
并返回
布尔值

Student student = new Student();
Predicate<Integer> p =  i -> student.check(i);

private Consumer c=Student::Consumer;/编译时错误

同样,没有新内容,
消费者
消费
T
并且不返回任何内容(返回类型为
void


我宁愿建议你去参观博物馆。编译第一行代码的原因是它可以表示
Student
类型的实例方法,例如
Student->Student.getGradeLevel
。这在使用
函数时很容易理解,因为这是在执行
p.apply()
时。
Student student = new Student();
Predicate<Integer> p =  i -> student.check(i);
BiPredicate<Student, Integer> biPredicate = (student, integer) -> student.check(integer);
BiPredicate<Student, Integer> biPredicate = Student::check;
Student student = new Student();
Consumer<Integer> c = integer -> student.consume(integer);
BiConsumer<Student, Integer> biConsumer = (student, integer) -> student.consume(integer);
BiConsumer<Student, Integer> biConsumer = Student::consume;