帶各位深入理解java1.8之supplier


supplier也是是用來創建對象的,但是不同於傳統的創建對象語法:new,看下面代碼:
public class TestSupplier {
private int age;
(www.0831jlyy.com)
TestSupplier(){
System.out.println(age);
}
public static void main(String[] args) {
//創建Supplier容器,聲明為TestSupplier類型,此時並不會調用對象的構造方法,即不會創建對象
Supplier<TestSupplier> sup= TestSupplier::new;
System.out.println("--------");
//調用get()方法,此時會調用對象的構造方法,即獲得到真正對象
sup.get();
//每次get都會調用構造方法,即獲取的對象不同
sup.get();
}
}
輸出結果:

--------
0
0
官方代碼及注釋:
/**(m.jlnk3659999.com)
* 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" rel="external nofollow" >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> {
(3g.xcjl0834.com)
/**
* Gets a result.
*
* @return a result
*/
T get();
}
根據代碼和官方注釋,我的個人理解:
1.supplier是個接口,有一個get()方法
2.語法 :
Supplier<TestSupplier> sup= TestSupplier::new;
3.每次調用get()方法時都會調用構造方法創建一個新對象。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM