函数式接口Supplier的用法

前言

最近看到公司写的rpc框架中,运用到了大量的函数式接口Supplier,下面将对supplier接口的具体使用简单介绍。

supplier接口定义

Java对其定义如下,自jdk1.8的时候新增的功能函数。

@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}

如上定义所示,Supplier 接口仅包含一个无参的方法: T get() ,用来获取一个泛型参数指定类型的对象数据。简单说这个接口只有一个get方法,传入一个泛型T,将返回一个泛型T。

具体使用

示例代码如下:

public class SupplierTest1 {
    public static void main(String[] args) {
        //传一个字符串:"hello world"
        Supplier<String> supplier = () -> "hello world";
        //将返回这个字符串
        System.out.println(supplier.get());

        //传一个对象
        Supplier<Student> studentSupplier = () -> new Student("123",12);
        //将返回一个对象
        System.out.println(studentSupplier.get());
        System.out.println(studentSupplier.get().getAge());
    }
}

返回结果:

hello world
Student(name=123, age=12)
12

在实际的项目开发中,主要用于数据缓存等场景。