Java – custom predicate link

I'm learning java 8 I'm trying to create a custom predict link method, as shown below

@FunctionalInterface
public interface Predicate<T> {

    boolean test(T t);

    default Predicate<T> and(Predicate<T> other){
        return t -> this.test(t) && other.test(t);
    }
}

It works when I define my predicate as described above, but if I try to implement it the same as below, it will give me a stackoverflow exception

@FunctionalInterface
public interface Predicate<T> {

    boolean test(T t);

    default Predicate<T> and(Predicate<T> other){
        //return t -> this.test(t) && other.test(t);
        return new Predicate<T>() {
            @Override
            public boolean test(T t) {
                return test(t) && other.test(t);
            }
        };
    }
}

You can explain why it gives me a Java 7 style stack overflow exception, and if I define it with lambda, don't give any exceptions

Solution

Test (T) is a recursive call to itself because the unqualified call is an anonymous class

So this Test (T) is because it refers to anonymous classes

Change to predict this. test(t)

@FunctionalInterface
public interface Predicate<T> {

    boolean test(T t);

    default Predicate<T> and(Predicate<T> other){
        //return t -> this.test(t) && other.test(t);
        return new Predicate<T>() {
            @Override
            public boolean test(T t) {
                return Predicate.this.test(t) && other.test(t);
            }
        };
    }
}

For details, see answer to "lambda this reference in Java"

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>