Java函数式接口@FunctionalInterface

一、源码

package java.lang;

import java.lang.annotation.*;

/**
 * An informative annotation type used to indicate that an interface
 * type declaration is intended to be a functional interface as
 * defined by the Java Language Specification.
 *
 * Conceptually, a functional interface has exactly one abstract
 * method.  Since {@linkplain java.lang.reflect.Method#isDefault()
 * default methods} have an implementation, they are not abstract.  If
 * an interface declares an abstract method overriding one of the
 * public methods of {@code java.lang.Object}, that also does
 * not count toward the interface's abstract method count
 * since any implementation of the interface will have an
 * implementation from {@code java.lang.Object} or elsewhere.
 *
 * 

Note that instances of functional interfaces can be created with * lambda expressions, method references, or constructor references. * *

If a type is annotated with this annotation type, compilers are * required to generate an error message unless: * *

    *
  • The type is an interface type and not an annotation type, enum, or class. *
  • The annotated type satisfies the requirements of a functional interface. *
* *

However, the compiler will treat any interface meeting the * definition of a functional interface as a functional interface * regardless of whether or not a {@code FunctionalInterface} * annotation is present on the interface declaration. * * @jls 4.3.2. The Class Object * @jls 9.8 Functional Interfaces * @jls 9.4.3 Interface Method Body * @since 1.8 */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface FunctionalInterface {}

二、@FunctionalInterface详解

@FunctionalInterface一种信息性注释类型用于指示接口类型声明是Java语言规范中定义的功能接口

如果用该注释类型注释了某个类型,则需要编译器生成错误消息,除非
(1)该类型是接口类型,而不是注释类型、枚举或类。
(2)带注释的类型满足功能接口的需求

该功能接口的需求(@FunctionalInterface注释的约束):
(1)接口有且只能有个一个抽象方法,只有方法定义,没有方法体
(2)在接口中覆写Object类中的public方法,不算是函数式接口的方法。

三、常用的封装好的函数式接口

1、Function
1)特性
(1)接收一个T类型的参数,返回一个R类型的结果。
(2)表示接受一个参数并产生一个结果的函数。
(3)这是一个函数接口,其函数方法是R apply(T t)

2)源码

package java.util.function;

import java.util.Objects;

/**
 * Represents a function that accepts one argument and produces a result.
 *
 * 

This is a functional interface * whose functional method is {@link #apply(Object)}. * * @param the type of the input to the function * @param the type of the result of the function * * @since 1.8 */ @FunctionalInterface public interface Function<T, R> { /** * Applies this function to the given argument. * * @param t the function argument * @return the function result */ R apply(T t); /** * Returns a composed function that first applies the {@code before} * function to its input, and then applies this function to the result. * If evaluation of either function throws an exception, it is relayed to * the caller of the composed function. * * @param the type of input to the {@code before} function, and to the * composed function * @param before the function to apply before this function is applied * @return a composed function that first applies the {@code before} * function and then applies this function * @throws NullPointerException if before is null * * @see #andThen(Function) */ default <V> Function<V, R> compose(Function<? super V, ? extends T> before) { Objects.requireNonNull(before); return (V v) -> apply(before.apply(v)); } /** * Returns a composed function that first applies this function to * its input, and then applies the {@code after} function to the result. * If evaluation of either function throws an exception, it is relayed to * the caller of the composed function. * * @param the type of output of the {@code after} function, and of the * composed function * @param after the function to apply after this function is applied * @return a composed function that first applies this function and then * applies the {@code after} function * @throws NullPointerException if after is null * * @see #compose(Function) */ default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) { Objects.requireNonNull(after); return (T t) -> after.apply(apply(t)); } /** * Returns a function that always returns its input argument. * * @param the type of the input and output objects to the function * @return a function that always returns its input argument */ static <T> Function<T, T> identity() { return t -> t; } }

2、Cosumer
1)特性
(1)接收一个T类型的参数,不返回值。
(2)表示接受单个输入参数且不返回结果的操作。与大多数其他功能接口不同,消费者被期望通过副作用进行操作。
(3)这是一个函数式接口,其函数方法是void accept(T t)

2)源码

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.
 *
 * 

This is a functional interface * whose functional method is {@link #accept(Object)}. * * @param 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. * * @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); }; } }

3、Predicate
可参考我的文章《Predicate》。

1)特性
(1)接收一个T类型的参数,返回一个boolean类型的结果。
(2)表示一个参数的谓词(布尔值函数)。
(3)这是一个功能接口,其功能方法是boolean test(T t)

2)源码
这里省略。

4、Supplier
1)特性
(1)不接受参数,返回一个T类型的结果。
(2)表示结果的提供者。
(3)没有要求每次调用供应商时都返回新的或不同的结果。
(4)这是一个函数式接口,其函数方法是T get()

2)源码

package java.util.function;

/**
 * Represents a supplier of results.
 *
 * 

There is no requirement that a new or distinct result be returned each * time the supplier is invoked. * *

This is a functional interface * whose functional method is {@link #get()}. * * @param the type of results supplied by this supplier * * @since 1.8 */ @FunctionalInterface public interface Supplier<T> { /** * Gets a result. * * @return a result */ T get(); }

实例:

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

public class FunctionalInterfaceTest {
    public static void main(String[] args) {
        Function<String, String> function = str -> str + "123";
        Consumer<String> consumer = System.out::println;
        Predicate<Integer> predicate = n -> n > 0;
        Supplier<String> supplier = () -> "supplier";

        System.out.println(function.apply("abc"));//abc123
        System.out.println(consumer);//FunctionalInterfaceTest$$Lambda$2/1149319664@6d03e736
        System.out.println(predicate.test(1));//true
        System.out.println(supplier.get());//supplier
    }
}

可参考文献:
https://www.cnblogs.com/jeffersonqin/p/12253457.html

你可能感兴趣的:(Java,java)