Java消费者接口

有人可以帮助我理解以下来自 Java 8 功能接口的代码根据我的理解,accept() 将其作为输入并对其进行处理,但在使用 andThen() 的情况下不返回任何值它是如何工作的


accept() 方法将类型 T 作为输入并且不返回任何值。


default Consumer<T> andThen(Consumer<? super T> after) {

        Objects.requireNonNull(after);

        return (T t) -> { accept(t); after.accept(t); };

}


慕无忌1623718
浏览 103回答 3
3回答

慕勒3428872

为了了解return从该 API 获取的内容,您可以尝试将实现可视化为:default Consumer<T> andThen(Consumer<? super T> after) {&nbsp; &nbsp; Objects.requireNonNull(after);&nbsp; &nbsp; return new Consumer<T>() { // return the complete Consumer implementation&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public void accept(T t) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Consumer.this.accept(t); // accept current consumer&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; after.accept(t); // and then accept the 'after' one.&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; };}现在把它联系起来(T t) -> { accept(t); after.accept(t); }&nbsp;是一个Consumer返回值,它确保accept首先编辑当前的,然后是提到的那个after。

一只甜甜圈

一个函数式接口必须只有一个抽象方法。但是,它可以有任意数量的静态方法和默认方法。的方法Consumer有:accept(T)这是 的单一抽象方法Consumer。它接受类型的单个通用参数T并且不返回任何内容(即void)。这是由 lambda 表达式或方法引用实现的方法。andThen(Consumer)这是默认方法。换句话说,它有一个实现,因此是非抽象的。该方法接受一个Consumer并返回另一个Consumer。因为它是一个默认方法,所以单一的抽象方法Consumer仍然存在accept(T)。上面解释了为什么Consumer可以有一个方法返回void.&nbsp;现在,当谈到 的实现时andThen,重要的是要意识到实际上涉及三个&nbsp;Consumers:被调用的实例andThen。引用的实例after。实例返回给调用者。如果您对代码进行格式化,那么并非所有内容都在同一行上,这可能更容易理解:default Consumer<T> andThen(Consumer<? super T> after) {&nbsp; &nbsp; Objects.requireNonNull(after);&nbsp; &nbsp; // Returns Consumer instance #3. The lambda is the implementation&nbsp; &nbsp; // of the 'accept' method.&nbsp; &nbsp; return (T t) -> {&nbsp; &nbsp; &nbsp; &nbsp; accept(t);&nbsp; &nbsp; &nbsp; &nbsp;// Invokes 'accept' on Consumer instance #1.&nbsp; &nbsp; &nbsp; &nbsp; after.accept(t); // Invokes 'accept' on Consumer instance #2.&nbsp; &nbsp; }}

慕尼黑8549860

我想我理解你的担忧。您想知道如果返回 voidandThen()之后为什么可以调用。accept()accept()问题是,您首先定义一个Consumer对象,然后在该实例上调用andThen()方法。例如:Consumer<String>&nbsp;consumer&nbsp;=&nbsp;s&nbsp;->&nbsp;System.out.println(s); consumer.andThen(s&nbsp;->&nbsp;System.out.println(s.toUpperCase()));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java