3 回答

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超6個(gè)贊
為了了解return從該 API 獲取的內(nèi)容,您可以嘗試將實(shí)現(xiàn)可視化為:
default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return new Consumer<T>() { // return the complete Consumer implementation
@Override
public void accept(T t) {
Consumer.this.accept(t); // accept current consumer
after.accept(t); // and then accept the 'after' one.
}
};
}
現(xiàn)在把它聯(lián)系起來(lái)
(T t) -> { accept(t); after.accept(t); }
是一個(gè)Consumer返回值,它確保accept首先編輯當(dāng)前的,然后是提到的那個(gè)after。

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超5個(gè)贊
一個(gè)函數(shù)式接口必須只有一個(gè)抽象方法。但是,它可以有任意數(shù)量的靜態(tài)方法和默認(rèn)方法。的方法Consumer
有:
accept(T)
這是 的單一抽象方法
Consumer
。它接受類型的單個(gè)通用參數(shù)T
并且不返回任何內(nèi)容(即void
)。這是由 lambda 表達(dá)式或方法引用實(shí)現(xiàn)的方法。andThen(Consumer)
這是默認(rèn)方法。換句話說(shuō),它有一個(gè)實(shí)現(xiàn),因此是非抽象的。該方法接受一個(gè)
Consumer
并返回另一個(gè)Consumer
。因?yàn)樗且粋€(gè)默認(rèn)方法,所以單一的抽象方法Consumer
仍然存在accept(T)
。
上面解釋了為什么Consumer
可以有一個(gè)方法返回void
. 現(xiàn)在,當(dāng)談到 的實(shí)現(xiàn)時(shí)andThen
,重要的是要意識(shí)到實(shí)際上涉及三個(gè) Consumer
s:
被調(diào)用的實(shí)例
andThen
。引用的實(shí)例
after
。實(shí)例返回給調(diào)用者。
如果您對(duì)代碼進(jìn)行格式化,那么并非所有內(nèi)容都在同一行上,這可能更容易理解:
default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
// Returns Consumer instance #3. The lambda is the implementation
// of the 'accept' method.
return (T t) -> {
accept(t); // Invokes 'accept' on Consumer instance #1.
after.accept(t); // Invokes 'accept' on Consumer instance #2.
}
}

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超11個(gè)贊
我想我理解你的擔(dān)憂。您想知道如果返回 voidandThen()
之后為什么可以調(diào)用。accept()
accept()
問題是,您首先定義一個(gè)Consumer
對(duì)象,然后在該實(shí)例上調(diào)用andThen()
方法。例如:
Consumer<String> consumer = s -> System.out.println(s); consumer.andThen(s -> System.out.println(s.toUpperCase()));
添加回答
舉報(bào)