简体   繁体   中英

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??

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:

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. 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.

Newer compiler 1 , starting with version 8 (I believe), add a (synthetic) method to the code, mostly like :

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM