[英]Java Predicate Interface - How the method is working - Though it is not implemented in my class
Though I have not implemented the method - test - which is in Predicate interface, how come the method is executed without any body in my class - inte??虽然我还没有实现 Predicate 接口中的方法 - 测试,但为什么在我的 class - inte 中没有任何主体执行该方法?
package newone;
import java.util.function.Predicate;
public class inte {
public static void main(String[] args) {
Predicate <Integer> p = i -> (i<19);
System.out.println( p.test(22));
}
@FunctionalInterface
public interface Predicate<T> {
boolean test(T var1);
}
Though I have not implemented the method - test虽然我还没有实现该方法 - 测试
You have, with the lambda expression:您拥有 lambda 表达式:
Predicate <Integer> p = i -> (i<19);
That's mostly like :这主要是:
Predicate<Integer> p = new Predicate<Integer>() {
@Override
public boolean test(Integer i) {
return i < 19;
}
};
The exact details in the bytecode are a little different, but for the most part you can think of a lambda expression as shorthand for creating an anonymous inner class.字节码中的具体细节略有不同,但在大多数情况下,您可以将 lambda 表达式视为创建匿名内部 class 的简写。 The compiler is able to perform other tricks to avoid creating extra classes in reality, at least in some cases - it depends on what your lambda expression does.编译器能够执行其他技巧以避免在现实中创建额外的类,至少在某些情况下 - 这取决于您的 lambda 表达式的作用。
Newer compiler 1 , starting with version 8 (I believe), add a (synthetic) method to the code, mostly like :较新的编译器1 ,从版本 8(我相信)开始,在代码中添加一个(合成)方法,主要是:
public class Inte {
public static void main(String[] args) {
Predicate<Integer> p = Inte::lambda$test$1;
...
}
// synthetic
private static boolean lambda$test$1(Integer i) {
return i < 19;
}
}
1 - alternatively, and before Java version 8, an additional class implementing the interface can be added (like an anonymous class) 1 - 或者,在 Java 版本 8 之前,可以添加一个额外的 class 实现接口(如匿名类)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.