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");

2. Function<String, T> fun2 = str -> new T(str);
    fun2.apply("test2");

注:每次調用get方法都會創建一個對象,下面的代碼中調用了兩次get方法,打印的hashcode是不一樣的!

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);
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章