版本
JDK8(JDK1.8)
Consumer函数式接口源码重点
1.Consumer函数式接口需要实现的方法是 void accept(T t),表示一个接受单个输入参数但不返回结果的操作。
2.Consumer andThen(Consumer<? super T> after) 用于拼接多个Consumer的accept(T t)方法,按顺序执行操作,如果前面的操作抛出异常,则后面的操作不会执行
3.Consumer接口方法
方法名 | 作用 |
---|---|
void accept(T t) | 对给定参数执行此操作 |
Consumer andThen(Consumer<? super T> after) | 返回一个组合的Consumer,它依次执行此操作和after操作 |
Consumer函数式接口源码
package java.util.function;
import java.util.Objects;
/**
* Represents an operation that accepts a single input argument and returns no
* result. Unlike most other functional interfaces, {@code Consumer} is expected
* to operate via side-effects.
* 表示接受单个输入参数但不返回结果的操作。
* 与大多数其他功能接口不同,Consumer预期通过副作用进行操作。
*
*
* <p>This is a <a href="package-summary.html">functional interface</a>
* whose functional method is {@link #accept(Object)}.
* 其函数方法是accept(Object)
*
* @param <T> the type of the input to the operation
*
* @since 1.8
*/
@FunctionalInterface
public interface Consumer<T> {
/**
* Performs this operation on the given argument.
* 对给定参数执行此操作。
*
* @param t the input argument 输入参数
*/
void accept(T t);
/**
* Returns a composed {@code Consumer} that performs, in sequence, this
* operation followed by the {@code after} operation. If performing either
* operation throws an exception, it is relayed to the caller of the
* composed operation. If performing this operation throws an exception,
* the {@code after} operation will not be performed.
* 返回一个组合的Consumer,它依次执行此操作和after操作。
* 如果执行任何一个操作都会引发异常,则会将异常转发给组合操作的调用方。
* 如果执行此操作引发异常,则不会执行after操作。
*
*
*
* @param after the operation to perform after this operation 此操作之后要执行的操作
* @return a composed {@code Consumer} that performs in sequence this
* operation followed by the {@code after} operation
* 一种组合的Consumer,按顺序执行此操作,然后执行after操作
* @throws NullPointerException if {@code after} is null 如果after为null
*/
default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return (T t) -> { accept(t); after.accept(t); };
}
}