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

问题描述 投票:2回答:1

根据文档,方法参考绝对不是静态调用。它适用于静态和非静态方法。当我们在给定的类中定义自己的非静态方法并尝试使用“方法引用”使用它时,在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);
    }
}
java lambda java-8 method-reference functional-interface
1个回答
2
投票

您必须同时使用Student方法的返回类型和形式参数类型,并使用适当的功能接口。


private Supplier<Integer> s = Student::supply; // compile-time error

Supplier<T>消耗nothing并返回T。一个例子是:

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

方法参考Student::supply的相关功能接口为Function<T, R>。以下两个是相等的:

Function<Student, Integer> function = student -> student.supply();
Function<Student, Integer> function = Student::supply;

// You have already used a method reference with the very same return and parameter types
Function<Student, Integer> p = Student::getGradeLevel;

private Predicate<Integer> p1= Student::check; //compile-time error

非常相似的问题,但Predicate<T> 消耗 T并返回Boolean

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

如果您想使用BiPredicate<T, R>方法参考,则可以使用产生BooleanStudent::check

BiPredicate<Student, Integer> biPredicate = (student, integer) -> student.check(integer);
BiPredicate<Student, Integer> biPredicate = Student::check;

private Consumer<Integer> c= Student::consume; / compile-time error

什么也没新,Consumer<T>消耗T并返回nothing(返回类型为void)。

Student student = new Student();
Consumer<Integer> c = integer -> student.consume(integer);

方法参考Student::consume适用于同时使用BiConsumer和某些StudentInteger

BiConsumer<Student, Integer> biConsumer = (student, integer) -> student.consume(integer);
BiConsumer<Student, Integer> biConsumer = Student::consume;
© www.soinside.com 2019 - 2024. All rights reserved.