了解功能接口方法和方法参考

时间:2017-06-10 20:18:05

标签: java lambda java-8 method-reference functional-interface

我想了解定义及其示例。

@FunctionalInterface public class Supplier<T> {
   public T get();
} 

它的用法是

Supplier<LocalDate> s1 = LocalDate::now;
Supplier<LocalDate> s2 = () -> LocalDate.now();
LocalDate d1 = s1.get();
LocalDate d2 = s2.get();

在此,我的理解是now是工厂方法,由s1s2引用。他们的类型是Supplier<LocalDate>。我从类型 LocalDate::now 返回LocalDate类型。

@FunctionalInterface public class Consumer<T> {
   void accept(T t);
}

用法,

Consumer<String> c1 = System.out::println;
Consumer<String> c2 = x -> System.out.println(x);

println是使用String的方法,不返回任何内容。

最后,

@FunctionalInterface public class Predicate<T> {
   boolean test(T t);
}
@FunctionalInterface public class BiPredicate<T, U> {
   boolean test(T t, U u);
}

他们的用法,

Predicate<String> p1 = String::isEmpty;
Predicate<String> p2 = x -> x.isEmpty();

BiPredicate<String, String> b1 = String::startsWith;
BiPredicate<String, String> b2 = (string, prefix) -> string.startsWith(prefix);

我的问题是Predicate有一个方法声明返回boolean并且没有传递任何内容。不是吗?在菱形运算符中左上角的上述两个示例中,存在返回类型或传递类型。因此,isEmpty声明没有传递类型,boolean用于返回。同一行为适用于BiPredicate startsWith仅采用String的一个参数类型,返回布尔值。它是如何工作的?因为我认为它应该与Predicate合作而不是BiPredicate。但是,在这种情况下,isEmpty不应与Predicate一起使用,但有效。我有点困惑。你会解释一下吗?

0 个答案:

没有答案