static inner class 什么时候被加载

时间:2023-03-09 01:23:33
static inner class 什么时候被加载

一直认为在加载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 静态类

基于静态内部类的此种特性可以来实现懒加载的单例模式,而且是线程安全的,实例代码如下:

public class Something {
private Something() {} private static class LazyHolder {
private static final Something INSTANCE = new Something();
} public static Something getInstance() { //只有在调用这个方法的时候才会生成唯一的Something 对象
return LazyHolder.INSTANCE;
}
}