一直认为在加载outer class 的同时也会加载inner class 并且完成静态变量和代码块的初始化,今天在维基百科上面看到 “The static class definitionLazyHolder within it is not initialized until the JVM determines that LazyHolder must be executed”,颠覆了我之前的观点,于是做下列实验来证明一下:
public class Initialize { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub helper h = new helper(); } } class helper{ static { System.out.println("helper is on going"); } private static class holder{ static { System.out.println("hodler is on going"); } } holder returnh(){ return new holder(); } }
执行的结果为:
helper is on going
也就是说只加载了helper 这个outer class 并初始化了静态块,而holder并没有被加载
public class Initialize { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub helper h = new helper(); h.returnh(); } } class helper{ static { System.out.println("helper is on going"); } private static class holder{ static { System.out.println("hodler is on going"); } } holder returnh(){ return new holder(); } }
执行结果为:
helper is on going
hodler is on going
也就是说inner static class 和 outer static class 的加载时机是一样的:
1. 访问静态类中的静态字段
2. 访问静态类中的静态方法
3. new 静态类
static inner class 什么时候被加载,布布扣,bubuko.com
原文:http://www.cnblogs.com/cruze/p/3725346.html