簡體   English   中英

自定義謂詞鏈接

[英]Custom Predicate chaining

我正在學習Java 8。 我正在嘗試創建自定義Predicate鏈接方法,如下所示

@FunctionalInterface
public interface Predicate<T> {

    boolean test(T t);

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

當我如上所述定義我的謂詞時它可以工作,但是如果我嘗試實現與下面相同的它,它會給我StackOverflow異常

@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);
            }
        };
    }
}

你可以解釋一下為什么它給我Java 7風格的stackoverflow異常,而如果我用lambda定義它,不要給出任何異常。

test(t)是對自身的遞歸調用,因為非限定調用是匿名類。

那么this.test(t)是,因為this指的是匿名類。

改為Predicate.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);
            }
        };
    }
}

有關更多詳細信息,請參閱“在Java中使用Lambda此引用”的答案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM