jvm-007(张龙老师jvm教程) 运行期常量和数组创建的本质分析

jvm-007

一、运行期常量与编译器常量不同:

对于在编译器无法确定的常量值,在被调用的时候,会引起常量所在类或者接口的初始化,此时不会触发常量传播优化。

代码示例:
 

public class TestCode03 {

    public static void main(String[] args) {
        System.out.println(Parent03.constant);
    }
}

class Parent03 {
    public static final String constant = UUID.randomUUID().toString();
    static {
        System.out.println("parent03 is inited");
    }
}

运行结果:

parent03 is inited 8ecb0e96-3536-40b8-9d20-11e6c3dfdebd

 

二、数组创建对象的本质分析

对于数组来说,其类型是在运行期间由虚拟机动态生成的,数组的元素类型不会被初始化。虚拟机创建的对象类型如下:

Test[] ary = new Test[2];

ary数组对象:[Lcn.com.Test

如果是个多维的数组,有几个维度就在类的全限定名前面添加几个左方括号 “[”。由虚拟机所创建的数组对象的父类是java.lang.Object类。Java将构成数组的元素称之为component(组件),指数组在去掉一个维度之后的类型。

public class TestCode04 {
    public static void main(String[] args) {
        Parent04[] ps = new Parent04[2]; // 不会引起Parent04类的初始化
        System.out.println(ps.getClass()); // class [Lcn.com.ccxi.test.jvm.Parent04;
        System.out.println(ps.getClass().getSuperclass()); // class java.lang.Object
    }
}

class Parent04 {
    static {
        System.out.println("---Parent04----初始化");
    }
}

运行结果:

class [Lcn.com.ccxi.test.jvm.Parent04; class java.lang.Object

以上结果显示,数组的创建不会导致数组元素类型的初始化。虚拟机创建的数组对象的类型以及其父类 java.lang.Object。

 

三、数组创建时的几个字节码指令:

1、原生类型的一个维度数组:

newarray:将一个原生类型的数组压入栈顶。

int[] intAry = new int[2]; byte[] byteAry = new byte[2]

2、引用类型的一个维度的数组:

anewarray:将一个引用类型的数组压入栈顶。

String[] stringAry = new String[3];

3、多维度类型的数组,基本元素类型包括原生类型和引用类型:

multianewarray:将一个多维度的数组压入栈顶。

int[][] intMulAry = new int[3][4]; String[][] strMulAry = new String[4][5];

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值