天天看點

java——除了new,你還會用supplier建立對象嗎?

作者專注于Java、架構、Linux、小程式、爬蟲、自動化等技術。 工作期間含淚整理出一些資料,微信搜尋【程式員高手之路】,回複 【java】【黑客】【爬蟲】【小程式】【面試】等關鍵字免費擷取資料。 

一、官方給的接口

使用FunctionalInterface注解修飾接口,隻有一個get方法

@FunctionalInterface
public interface Supplier<T> {

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

二、解析

如下列代碼所示:

使用Supplier建立對象,文法結構:

無參數:

1. Supplier<T> instance = T::new;

2. Supplier<T> instance = () -> new T();

有參數:

1. Function<String, T> fun = T::new;

    fun.apply("test");

public class TestSupplier {
	public static void main(String[] args) {
		//無參數1:
		Supplier<TestSupplier> sup = TestSupplier::new;
		sup.get();
		sup.get();
		//無參數2:
		Supplier<TestSupplier> sup2 = () -> new TestSupplier();
		sup2.get();
		sup2.get();
		
		//有參數1:
		Function<String, TestSupplier> fun = TestSupplier::new;
		fun.apply("test");
		//有參數2:
		Function<String, TestSupplier> fun2 = str -> new TestSupplier(str);
		fun2.apply("test2");
	}

	public TestSupplier() {
		System.out.println(this.hashCode());
	}
	
	public TestSupplier(String str) {
		System.out.println(this.hashCode() + ",參數:" + str);
	}
}