这里,对静态方法 isPrime() 的引用作为第一个参数传递给 numTest()。
这是可行的,因为 isPrime 与 IntPredicate 函数接口兼容。因此,
表达式 MyIntPredicates::isPrime 计算为对对象的引用,其中isPrime()提供了IntPredicate中test()的实现。
isPrime() 如何提供 test() 的实现使用除 test() 之外的不同引用/名称。我想这就是 Java 8 中这样做的意义所在,它提供了更多的灵活性和可能性。有人可以解释一下这是否是新的吗?它是如何运作的?
Thanks !
//Demonstrate a method reference for a static method.
//A functional interface for numeric predicates that operate
//on integer values.
interface IntPredicate {
//the abstact to be implemented with something compatible
boolean test(int n);
}
// This class defines three static methods that check an integer
// against some condition.
class MyIntPredicates {
// A static method that returns true if a number is prime.
static boolean isPrime(int n) {
if (n < 2)
return false;
for (int i = 2; i <= n / i; i++) {
if ((n % i) == 0)
return false;
}
return true;
}
// A static method that returns true if a number is even.
static boolean isEven(int n) {
return (n % 2) == 0;
}
// A static method that returns true if a number is positive.
static boolean isPositive(int n) {
return n > 0;
}
}
public class MethodRefDemo {
// This method has a functional interface as the type of its
// first parameter. Thus, it can be passed a reference to any
// instance of that interface, including one created by a
// method reference.
static boolean numTest(IntPredicate p, int v) {
return p.test(v);
}
public static void main(String args[]) {
boolean result;
// Here, a method reference to isPrime is passed to numTest().
result = numTest(MyIntPredicates::isPrime, 17);
if (result)
System.out.println("17 is prime.");
// Next, a method reference to isEven is used.
result = numTest(MyIntPredicates::isEven, 12);
if (result)
System.out.println("12 is even.");
// Now, a method reference to isPositive is passed.
result = numTest(MyIntPredicates::isPositive, 11);
if (result)
System.out.println("11 is positive.");
}
}
这是 lambda 工作的一个示例。它是 java 8 中的新增功能,它基本上允许运行时使用您定义的实现为您创建功能接口的实例。
布莱恩·戈茨 (Brian Goetz) 写过一篇doc http://cr.openjdk.java.net/~briangoetz/lambda/lambda-translation.html关于 lambda(和方法引用)在编译和运行时如何工作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)