靜態內部類的類加載順序

一個類被加載,當且僅當其某個靜態成員(靜態域、構造器、靜態方法等)被調用時發生。 學習

那麼加載一個類時,靜態內部類是否是被看作「靜態代碼塊」同時被加載了?下面咱們作一個實驗來看一下。 spa

Java代碼  
  1. public class Outer {  
  2.     static {  
  3.         System.out.println("load outer class...");  
  4.     }  
  5.       
  6.     //靜態內部類  
  7.     static class StaticInner {  
  8.         static {  
  9.             System.out.println("load static inner class...");  
  10.         }  
  11.           
  12.         static void staticInnerMethod() {  
  13.             System.out.println("static inner method...");  
  14.         }  
  15.     }  
  16.           
  17.     public static void main(String[] args) {  
  18.         Outer outer = new Outer();      //此刻其內部類是否也會被加載?  
  19.          System.out.println("===========分割線===========");  
  20.         Outer.StaticInner.staticInnerMethod();      //調用內部類的靜態方法  
  21.     }  
  22. }  


運行結果: 
load outer class... 
==========分割線========== 
load static inner class... 
static inner method... 

    調用構造方法時,外部類Outer被加載,但這時其靜態內部類StaticInner卻未被加載。直到調用該內部類的靜態方法(在分割線如下),StaticInner才被加載。

延伸學習:對象

根據內部類不會在其外部類被加載的同時被加載的事實,咱們能夠引伸出單例模式的一種實現方式: 靜態內部類資源

Java代碼  
  1. public class Singleton {  
  2.     private Singleton() {}  
  3.       
  4.     static class SingletonHolder {  
  5.         private static final Singleton instance = new Singleton();  
  6.     }  
  7.       
  8.     public static Singleton getInstance() {  
  9.         return SingletonHolder.instance;  
  10.     }  
  11. }  

    該「靜態內部類」實現單例模式的方式,在單例對象佔用資源大,須要延時加載的狀況下優選。get

相關文章
相關標籤/搜索