載入一個類時,其內部類是否同時被載入?靜態內部類單例模式_設計模式

來源:互聯網
上載者:User
載入一個類時,其內部類是否同時被載入。下面我們做一個實驗來看一下。 
Java代碼   public class Outer {       static {           System.out.println("load outer class...");       }              //靜態內部類       static class StaticInner {           static {               System.out.println("load static inner class...");           }                      static void staticInnerMethod() {               System.out.println("static inner method...");           }       }                  public static void main(String[] args) {           Outer outer = new Outer();      //此刻其內部類是否也會被載入。            System.out.println("===========分割線===========");           Outer.StaticInner.staticInnerMethod();      //調用內部類的靜態方法       }   }  
運行結果: 
load outer class... 
==========分割線========== 
load static inner class... 
static inner method... 

    調用構造方法時,外部類Outer被載入,但這時其靜態內部類StaticInner卻未被載入。直到調用該內部類的靜態方法(在分割線以下),StaticInner才被載入。可以做類似的實驗驗證非靜態內部類的情況。 
     結論:載入一個類時,其內部類不會同時被載入。一個類被載入,若且唯若其某個靜態成員(靜態域、構造器、靜態方法等)被調用時發生。  

    根據內部類不會在其外部類被載入的同時被載入的事實,我們可以引申出單例模式的一種實現方式: 
Java代碼   public class Singleton {       private Singleton() {}              static class SingletonHolder {           private static final Singleton instance = new Singleton();       }              public static Singleton getInstance() {           return SingletonHolder.instance;       }   }  
    該實現方式比較簡單,而且既實現了由前述事實所保證的惰性初始化(Lazy-Initialazation),又由JVM保證了多線程並發訪問的正確性。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.