函数式接口consumer

@FunctionalInterface

1.此注解表明该接口是一个函数式接口,所谓的函数式接口,是指“有且只有一个抽象方法”
2.接口中的静态方法,默认方法(default修饰),以及java.lang.Object类中的方法都不算抽象方法。
3.如果接口符合函数式接口的定义,则此注解加不加无所谓,加了会方便编译器检查。如果不符合函数式接口定义,则此注解会报错。

先来看下stream的函数接口



@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.
*
* @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
* @throws NullPointerException if {@code after} is null
*/
default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return (T t) -> { accept(t); after.accept(t); };
}
}




//List
@Override public void forEach(Consumer<? super E> action) {        //函数接口 Objects.requireNonNull(action); final int expectedModCount = modCount; @SuppressWarnings("unchecked") final E[] elementData = (E[]) this.elementData; final int size = this.size; for (int i=0; modCount == expectedModCount && i < size; i++) { action.accept(elementData[i]);              //调用具体实现 } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } }


list.forEach(s -> System.out.println(s))

 

示例二

//注解用于检查是否是函数式接口,default、static除外,有且只有一个抽象方法
@FunctionalInterface
public interface FunctionTest {
    void saveMessage(String message);

    default void saveMessage2(){
        System.out.println(" defaultMethod.....");
    };

    static void aaa(){
        System.out.println("static method .....");
    }
}



public class Test1 {
public static void main(String[] args) {
FunctionTest functionTest = new FunctionTest() {
@Override
public void saveMessage(String message) {
System.out.println("111111");
}
};

FunctionTest functionTest2 = s -> System.out.println(s);

functionTest2.saveMessage("saveMessage........");

Consumer<Integer> consumer = new Consumer<Integer>() {
@Override
public void accept(Integer o) {
System.out.println(o);
}
};

Consumer<Integer> consumer1 = s -> System.out.println(s);

consumer1.accept(11111);

}
}
 

 

接口定义了抽象的方法,我们先使用impl或者lambda实现了函数式接口,后面抽象方法调用的时候(如consumer.accept),就是调用具体的实例方法。

java.util.function jdk还提供了其他的接口供使用,很方便,可以不需要自己定义接口,也不用写具体的impl文件。
上一篇:kafka java api


下一篇:interface Consumer, package java.util.function, since jre1.8