静态内部类的类加载顺序

一个类被加载,当且仅当其某个静态成员(静态域、构造器、静态方法等)被调用时发生。 

那么加载一个类时,静态内部类是不是被看做“静态代码块”同时被加载了?下面我们做一个实验来看一下。 

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. }  

    该“静态内部类”实现单例模式的方式,在单例对象占用资源大,需要延时加载的情况下优选。

原文地址:https://www.cnblogs.com/paul011/p/8574650.html