java惰性初始化

來源:互聯網
上載者:User

初始化有效地實現了儘可能的惰性。僅使用.class文法來獲得對類的引用不會引發初始化。但是為了產生Class引用,Class.forName()

立即就進行了初始化

如果一個static final值是編譯期常量,那麼這個值就不需要對類進行初始化就能擷取,但是如果將一個網域設定成static和final的,還不足

以確保這種行為,對它的訪問就會強制進行類的初始化,因為他不是一個編譯期常量

如果一個static域不是final的,那麼在對他訪問時,總是要求她在被讀取之前,要先進行連結(為這個域分配儲存空間)和初始化(初始化

該儲存空間)

為了使用類而做的準備工作包含三個步驟:

1.載入,這是由類載入器執行的。該步驟將尋找位元組碼(通常在classpath所指定的路徑中尋找,但這並非必須的),並從這些位元組碼中建立一個Class對象。

2.連結,在連結階段將驗證類的位元組碼,為靜態域分配儲存空間,並且如果必須的話,將解析這個類建立的對其他類的所有引用。

3.初始化,如果該類具有超類,則對其進行初始化,初始化靜態域和靜態初始化塊。

初始化被延遲到對靜態方法(構造器隱式地是靜態)或者非常數靜態域進行首次引用時才執行。

/** *  */package com.runtech;import java.util.Random;public class Demo002 {public static Random random = new Random(47);public static void main(String[] args) {Class c1 = Initable1.class;//不會初始化System.out.println(Initable1.staticFinal01);//編譯期常量System.out.println(Initable1.staticFinal02);//強制類的初始化,非編譯期常量System.out.println("-----------------------------------");try {Class c2 = Class.forName("com.runtech.Initable1");//直接就初始化了System.out.println(Initable2.staticFinal01);System.out.println(Initable2.staticFinal02);} catch (ClassNotFoundException e) {e.printStackTrace();}System.out.println("-----------------------------------");Class c3 = Initable3.class;System.out.println(Initable3.staticFinal01);//非編譯期常量System.out.println(Initable3.staticFinal02);System.out.println("-----------------------------------");new Initable2();System.out.println(Initable2.staticFinal01);System.out.println(Initable2.staticFinal02);}}class Initable1 {static final int staticFinal01 = 47;static final int staticFinal02 = Demo002.random.nextInt(1000);static {System.out.println("Initable1 static");}public Initable1() {System.out.println("Initable1 Constructor");}}class Initable2 {static int staticFinal01 = 12;static final int staticFinal02 = Demo002.random.nextInt(1000);static {System.out.println("Initable2 static");}public Initable2() {System.out.println("Initable2 Constructor");}}class Initable3 {static int staticFinal01 = 12;static final int staticFinal02 = Demo002.random.nextInt(1000);static {System.out.println("Initable3 static");}public Initable3() {System.out.println("Initable3 Constructor");}}

輸出 :

47
Initable1 static
258
-----------------------------------
Initable2 static
12
555
-----------------------------------
Initable3 static
12
693
-----------------------------------
Initable2 Constructor
12
555

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.