• 03.编译期常量与运行期常量的区别与数组创建本质分析


    编译期常量

    当一个常量的值并非编译期间可以确定的,那么其值就不会放到调用类的常量池中

    这时在程序运行时,会主动使用这个常量所在的类,显然会导致这个类会被初始化,输出静态代码块中语句

    public class MyTest3 {
        public static void main(String[] args) {
            System.out.println(MyParent3.str);
        }
    }
    
    class MyParent3 {
        public static final String str = UUID.randomUUID().toString();
    
        static {
            System.out.println("MyParent3 static code");
        }
    }
    

    运行期常量

    new 对象时,对类的首次主动使用,以下语句会被输出

    public class MyTest {
        public static void main(String[] args) {
            MyParent4 myParent4 = new MyParent4();
            MyParent4 myParent42 = new MyParent4();
        }
    }
    
    class MyParent4 {
        static {
            System.out.println("MyParent4 static block");
        }
    }
    

    数组创建的本质

    对数组实例来说,其实例是由 JVM 在运行期动态生成的,表示为

    [Lcn.duniqb.jvm.classloader.MyParent4
    

    动态生成的类型,其父类型就是 Object

    对于数组来说,JavaDoc 经常将构成数组元素为 Component,实际上就是将数组降低一个维度的类型

    语句不会被输出

    public class MyTest4 {
        public static void main(String[] args) {
            MyParent4[] myParent42 = new MyParent4[1];
            System.out.println(myParent42.getClass());
    
            MyParent4[][] myParent421 = new MyParent4[1][1];
            System.out.println(myParent421.getClass());
    
            System.out.println(myParent42.getClass().getSuperclass());
            System.out.println(myParent421.getClass().getSuperclass());
        }
    }
    
    class MyParent4 {
        static {
            System.out.println("MyParent4 static block");
        }
    }
    

    助记符

    • anewarray
      • 表示创建一个引用类型的 (如类,接口,数组) 数组,并将其压入栈顶
    • newarray
      • 表示创建一个指定的原始类型 (如int,float,char等) 的数组,并将其引用值压入栈顶

    没有修不好的电脑
  • 相关阅读:
    转:backbone.js源码解析:extend、Backbone.View
    转:前端单元测试总结
    转:JavaScript Promises相当酷:一种有趣的方案库
    npm发布模块
    转:nodejs npm常用命令
    nodejs守护进程forever
    转:SublimeText2 快捷键一览表
    转载7 Essential JavaScript Functions
    用node生成svg图片
    关于performance
  • 原文地址:https://www.cnblogs.com/duniqb/p/12702451.html
Copyright © 2020-2023  润新知