• 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;
        }
    }
  • 相关阅读:
    [刘阳Java]_eayui-pagination分页组件_第5讲
    [刘阳Java]_easyui-draggable拖动组件_第4讲
    [刘阳Java]_easyui-panel组件入门级_第3讲
    [刘阳Java]_TortoiseSVN基础应用_第1讲
    [刘阳Java]_SpringMVC文件上传第2季_第11讲
    [刘阳Java]_Spring中IntrospectorCleanupListener的用途【补充】_第16讲
    使用fetch代替ajax请求 post传递方式
    react购物车demo
    react-redux异步数据操作
    redux模块化demo
  • 原文地址:https://www.cnblogs.com/cruze/p/3725346.html
Copyright © 2020-2023  润新知