1、Supplier简介
supplier接口是JAVA8以后配合lambda表达式和函数式接口编程(FunctionInterface,以下简称FI)组合使用的一个接口,对外表现为双冒号"::",顺便说下"->"符号对应的是Function接口中的Reply方法例如:
Supplier<Person> persionSupplier = Person::new;
Arrays.asList("a","b","c").forEach(e->System.out.println(e));
在Java8中增加的接口Supplier,最适合用于表示工厂。带有Supplier的方法,通常应该限制输入工厂的类型参数使用有限制的通配符类型,以便客户端能够传入一个工厂,来创建指定类型的任意子类型。
应该将这些资源或者工厂传给构造器(或者静态工厂、或者构建器),通过他们来创建类。这个实践就被称做依赖注入,它极大地提高了类的灵活性、可重用性和可测试性。
简而言之,Supplier就是用来创建对象的,相当于new。
2、代码实例
package com.guor.effective.chapter2.java8;
import java.util.function.Supplier;
public class TestSupplier {
private int age;
public static void test(){
System.out.println("Java8新特性,Supplier");
}
TestSupplier(){
System.out.println("构造函数,age,"+age);
}
public static void main(String[] args) {
//创建Supplier容器,声明为TestSupplier类型,此时并不会调用对象的构造方法,即不会创建对象
Supplier<TestSupplier> sup= TestSupplier::new;
sup.get().test();
System.out.println("--------");
//调用get()方法,此时会调用对象的构造方法,即获得到真正对象
sup.get();
//每次get都会调用构造方法,即获取的对象不同
System.out.println("是否是相同的对象实例"+sup.get()==sup.get().toString());
}
}
3、控制台输出
4、通俗易懂
private static int getMax(Supplier<Integer> supplier) {
return supplier.get();
}
private static void test01() {
Integer[] arr = {10,2,5,3,9,4};
int max2 = getMax(() -> {
int max = 0;
for(Integer i : arr) {
if(i > max) {
max = i;
}
}
return max;
});
System.out.println(max2);//10
}
二、Supplier源码分析
Supplier接口源码中只有一个get()方法。
每次get都会调用构造方法,即获取的对象不同。
/*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package java.util.function;
/**
* Represents a supplier of results.
*
* <p>There is no requirement that a new or distinct result be returned each
* time the supplier is invoked.
*
* <p>This is a <a href="package-summary.html">functional interface</a>
* whose functional method is {@link #get()}.
*
* @param <T> the type of results supplied by this supplier
*
* @since 1.8
*/
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
最后
由于文案过于长,在此就不一一介绍了,这份Java后端架构进阶笔记内容包括:Java集合,JVM、Java并发、微服务、SpringNetty与 RPC 、网络、日志 、Zookeeper 、Kafka 、RabbitMQ 、Hbase 、MongoDB、Cassandra 、Java基础、负载均衡、数据库、一致性算法、Java算法、数据结构、分布式缓存等等知识详解。
本知识体系适合于所有Java程序员学习,关于以上目录中的知识点都有详细的讲解及介绍,掌握该知识点的所有内容对你会有一个质的提升,其中也总结了很多面试过程中遇到的题目以及有对应的视频解析总结。
有需要的朋友可以点击这里免费获取
mg-iqRhmhPR-1628596730434)]
本知识体系适合于所有Java程序员学习,关于以上目录中的知识点都有详细的讲解及介绍,掌握该知识点的所有内容对你会有一个质的提升,其中也总结了很多面试过程中遇到的题目以及有对应的视频解析总结。
有需要的朋友可以点击这里免费获取
[外链图片转存中…(img-EYGs2rTF-1628596730436)]