Kotlin字节码层探究构造函数与成员变量和init代码块执行顺序

之前写了一篇文章,从Java语法的角度分析了Kotlin构造函数、成员变量初始化、init代码块三者的执行顺序:

Kotlin构造函数与成员变量和init代码块执行顺序详细讲解

这次再从字节码的角度分析它们的执行顺序。

还是用之前那个例子:

class InitOrderDemo(name: String) {
    val firstProperty = "First property: $name".also(::println)
    init {
        println("First initializer block that prints ${name}")
    }
    val secondProperty = "Second property: ${name.length}".also(::println)
    init {
        println("Second initializer block that prints ${name.length}")
    }
}

调用InitOrderDemo(“hello”)打印的结果如下:

First property: hello
First initializer block that prints hello
Second property: 5
Second initializer block that prints 5

可以看到执行顺序,是按照它们声明的顺序执行。

将上面Koltin代码转成字节码之后,显示内容如下:

// ================com/devnn/javalib/InitOrderDemo.class =================
// class version 52.0 (52)
// access flags 0x31
public final class com/devnn/javalib/InitOrderDemo {
  // access flags 0x12
  private final Ljava/lang/String; firstProperty
  @Lorg/jetbrains/annotations/NotNull;() // invisible
  // access flags 0x11
  public final getFirstProperty()Ljava/lang/String;
  @Lorg/jetbrains/annotations/NotNull;() // invisible
   L0
    LINENUMBER 4 L0
    ALOAD 0
    GETFIELD com/devnn/javalib/InitOrderDemo.firstProperty : Ljava/lang/String;
    ARETURN
   L1
    LOCALVARIABLE this Lcom/devnn/javalib/InitOrderDemo; L0 L1 0
    MAXSTACK = 1
    MAXLOCALS = 1
  // access flags 0x12
  private final Ljava/lang/String; secondProperty
  @Lorg/jetbrains/annotations/NotNull;() // invisible
  // access flags 0x11
  public final getSecondProperty()Ljava/lang/String;
  @Lorg/jetbrains/annotations/NotNull;() // invisible
   L0
    LINENUMBER 10 L0
    ALOAD 0
    GETFIELD com/devnn/javalib/InitOrderDemo.secondProperty : Ljava/lang/String;
    ARETURN
   L1
    LOCALVARIABLE this Lcom/devnn/javalib/InitOrderDemo; L0 L1 0
    MAXSTACK = 1
    MAXLOCALS = 1
  // access flags 0x1
  public <init>(Ljava/lang/String;)V
    // annotable parameter count: 1 (visible)
    // annotable parameter count: 1 (invisible)
    @Lorg/jetbrains/annotations/NotNull;() // invisible, parameter 0
   L0
    ALOAD 1
    LDC "name"
    INVOKESTATIC kotlin/jvm/internal/Intrinsics.checkNotNullParameter (Ljava/lang/Object;Ljava/lang/String;)V
   L1
    LINENUMBER 3 L1
    ALOAD 0
    INVOKESPECIAL java/lang/Object.<init> ()V
   L2
    LINENUMBER 4 L2
    ALOAD 0
    NEW java/lang/StringBuilder
    DUP
    INVOKESPECIAL java/lang/StringBuilder.<init> ()V
    LDC "First property: "
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    ALOAD 1
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    INVOKEVIRTUAL java/lang/StringBuilder.toString ()Ljava/lang/String;
    ASTORE 2
   L3
    ALOAD 2
    ASTORE 3
   L4
    LINENUMBER 17 L4
    ASTORE 5
   L5
    ICONST_0
    ISTORE 4
   L6
    LINENUMBER 4 L6
   L7
    GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
    ALOAD 3
    INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/Object;)V
   L8
   L9
   L10
    GETSTATIC kotlin/Unit.INSTANCE : Lkotlin/Unit;
    ASTORE 6
    ALOAD 5
   L11
    LINENUMBER 4 L11
   L12
    ALOAD 2
   L13
    PUTFIELD com/devnn/javalib/InitOrderDemo.firstProperty : Ljava/lang/String;
   L14
    LINENUMBER 6 L14
    NOP
   L15
    LINENUMBER 7 L15
    NEW java/lang/StringBuilder
    DUP
    INVOKESPECIAL java/lang/StringBuilder.<init> ()V
    LDC "First initializer block that prints "
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    ALOAD 1
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    INVOKEVIRTUAL java/lang/StringBuilder.toString ()Ljava/lang/String;
    ASTORE 2
   L16
    GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
    ALOAD 2
    INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/Object;)V
   L17
   L18
    LINENUMBER 8 L18
    NOP
   L19
    LINENUMBER 10 L19
    ALOAD 0
    NEW java/lang/StringBuilder
    DUP
    INVOKESPECIAL java/lang/StringBuilder.<init> ()V
    LDC "Second property: "
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    ALOAD 1
    INVOKEVIRTUAL java/lang/String.length ()I
    INVOKEVIRTUAL java/lang/StringBuilder.append (I)Ljava/lang/StringBuilder;
    INVOKEVIRTUAL java/lang/StringBuilder.toString ()Ljava/lang/String;
    ASTORE 2
   L20
    ALOAD 2
    ASTORE 3
   L21
    LINENUMBER 17 L21
    ASTORE 5
   L22
    ICONST_0
    ISTORE 4
   L23
    LINENUMBER 10 L23
   L24
    GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
    ALOAD 3
    INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/Object;)V
   L25
   L26
   L27
    GETSTATIC kotlin/Unit.INSTANCE : Lkotlin/Unit;
    ASTORE 6
    ALOAD 5
   L28
    LINENUMBER 10 L28
   L29
    ALOAD 2
   L30
    PUTFIELD com/devnn/javalib/InitOrderDemo.secondProperty : Ljava/lang/String;
   L31
    LINENUMBER 12 L31
    NOP
   L32
    LINENUMBER 13 L32
    NEW java/lang/StringBuilder
    DUP
    INVOKESPECIAL java/lang/StringBuilder.<init> ()V
    LDC "Second initializer block that prints "
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    ALOAD 1
    INVOKEVIRTUAL java/lang/String.length ()I
    INVOKEVIRTUAL java/lang/StringBuilder.append (I)Ljava/lang/StringBuilder;
    INVOKEVIRTUAL java/lang/StringBuilder.toString ()Ljava/lang/String;
    ASTORE 2
   L33
    GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
    ALOAD 2
    INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/Object;)V
   L34
   L35
    LINENUMBER 14 L35
    RETURN
   L36
    LOCALVARIABLE p1 Ljava/lang/Object; L5 L10 3
    LOCALVARIABLE $i$a$-unknown-InitOrderDemo$firstProperty$1 I L6 L10 4
    LOCALVARIABLE p1 Ljava/lang/Object; L22 L27 3
    LOCALVARIABLE $i$a$-unknown-InitOrderDemo$secondProperty$1 I L23 L27 4
    LOCALVARIABLE this Lcom/devnn/javalib/InitOrderDemo; L0 L36 0
    LOCALVARIABLE name Ljava/lang/String; L0 L36 1
    MAXSTACK = 3
    MAXLOCALS = 7
}

可以看到上面的构造函数、成员变量初始化和init代码块,按照声明都被放到了字节码的init代码块中了。

字节码的init初始化器其实就是类的构造函数。将Java代码转成字节码也是存在init构造函数。

下面看一个Java示例,加深对字节码的init初始化块的认识。

package com.devnn.javalib;
public class JavaInit {
    String firstName = "Steven";
    {
        System.out.println("This is init block");
    }
    JavaInit(String secondName) {
        System.out.println("firstName=" + firstName);
        System.out.println("secondName=" + secondName);
    }
    public static void main(String[] args) {
        new JavaInit("Jobs");
    }
}

运行main函数打印结果如下:

This is init block
firstName=Steven
secondName=Jobs

将上面的JavaInit类转成字节码之后的内容如下:

// class version 51.0 (51)
// access flags 0x21
public class com/devnn/javalib/JavaInit {
  // compiled from: JavaInit.java
  // access flags 0x0
  Ljava/lang/String; firstName
  // access flags 0x0
  <init>(Ljava/lang/String;)V
   L0
    LINENUMBER 10 L0
    ALOAD 0
    INVOKESPECIAL java/lang/Object.<init> ()V
   L1
    LINENUMBER 4 L1
    ALOAD 0
    LDC "Steven"
    PUTFIELD com/devnn/javalib/JavaInit.firstName : Ljava/lang/String;
   L2
    LINENUMBER 7 L2
    GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
    LDC "This is init block"
    INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/String;)V
   L3
    LINENUMBER 11 L3
    GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
    NEW java/lang/StringBuilder
    DUP
    INVOKESPECIAL java/lang/StringBuilder.<init> ()V
    LDC "firstName="
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    ALOAD 0
    GETFIELD com/devnn/javalib/JavaInit.firstName : Ljava/lang/String;
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    INVOKEVIRTUAL java/lang/StringBuilder.toString ()Ljava/lang/String;
    INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/String;)V
   L4
    LINENUMBER 12 L4
    GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
    NEW java/lang/StringBuilder
    DUP
    INVOKESPECIAL java/lang/StringBuilder.<init> ()V
    LDC "secondName="
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    ALOAD 1
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    INVOKEVIRTUAL java/lang/StringBuilder.toString ()Ljava/lang/String;
    INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/String;)V
   L5
    LINENUMBER 13 L5
    RETURN
   L6
    LOCALVARIABLE this Lcom/devnn/javalib/JavaInit; L0 L6 0
    LOCALVARIABLE secondName Ljava/lang/String; L0 L6 1
    MAXSTACK = 3
    MAXLOCALS = 2
  // access flags 0x9
  public static main([Ljava/lang/String;)V
   L0
    LINENUMBER 16 L0
    NEW com/devnn/javalib/JavaInit
    DUP
    LDC "Jobs"
    INVOKESPECIAL com/devnn/javalib/JavaInit.<init> (Ljava/lang/String;)V
    POP
   L1
    LINENUMBER 17 L1
    RETURN
   L2
    LOCALVARIABLE args [Ljava/lang/String; L0 L2 0
    MAXSTACK = 3
    MAXLOCALS = 1
}

可见,Java类的成员变量初始化、构造函数、构造块同样都被拷贝进了init代码块中。那么它们是否存在顺序问题呢?

将上面JavaInit类的firname成员变量放到初始化块下面试试:

package com.devnn.javalib;
public class JavaInit {
    {
        System.out.println("This is init block");
    }
    JavaInit(String secondName) {
        System.out.println("firstName=" + firstName);
        System.out.println("secondName=" + secondName);
    }
    String firstName = "Steven";
    public static void main(String[] args) {
        new JavaInit("Jobs");
    }
}

查看字节码:

// class version 51.0 (51)
// access flags 0x21
public class com/devnn/javalib/JavaInit {
  // compiled from: JavaInit.java
  // access flags 0x0
  Ljava/lang/String; firstName
  // access flags 0x0
  <init>(Ljava/lang/String;)V
   L0
    LINENUMBER 8 L0
    ALOAD 0
    INVOKESPECIAL java/lang/Object.<init> ()V
   L1
    LINENUMBER 5 L1
    GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
    LDC "This is init block"
    INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/String;)V
   L2
    LINENUMBER 13 L2
    ALOAD 0
    LDC "Steven"
    PUTFIELD com/devnn/javalib/JavaInit.firstName : Ljava/lang/String;
   L3
    LINENUMBER 9 L3
    GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
    NEW java/lang/StringBuilder
    DUP
    INVOKESPECIAL java/lang/StringBuilder.<init> ()V
    LDC "firstName="
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    ALOAD 0
    GETFIELD com/devnn/javalib/JavaInit.firstName : Ljava/lang/String;
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    INVOKEVIRTUAL java/lang/StringBuilder.toString ()Ljava/lang/String;
    INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/String;)V
   L4
    LINENUMBER 10 L4
    GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
    NEW java/lang/StringBuilder
    DUP
    INVOKESPECIAL java/lang/StringBuilder.<init> ()V
    LDC "secondName="
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    ALOAD 1
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    INVOKEVIRTUAL java/lang/StringBuilder.toString ()Ljava/lang/String;
    INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/String;)V
   L5
    LINENUMBER 11 L5
    RETURN
   L6
    LOCALVARIABLE this Lcom/devnn/javalib/JavaInit; L0 L6 0
    LOCALVARIABLE secondName Ljava/lang/String; L0 L6 1
    MAXSTACK = 3
    MAXLOCALS = 2
  // access flags 0x9
  public static main([Ljava/lang/String;)V
   L0
    LINENUMBER 17 L0
    NEW com/devnn/javalib/JavaInit
    DUP
    LDC "Jobs"
    INVOKESPECIAL com/devnn/javalib/JavaInit.<init> (Ljava/lang/String;)V
    POP
   L1
    LINENUMBER 18 L1
    RETURN
   L2
    LOCALVARIABLE args [Ljava/lang/String; L0 L2 0
    MAXSTACK = 3
    MAXLOCALS = 1
}

可见,Java类的成员变量初始化、构造函数、构造块同样都被拷贝进了字节码init代码块中。Java的成员变量初始化和构造块也是按声明顺序执行。不同的是,Java的构造函数代码始终放在了字节码init代码块的后面。

字节码的init初始化块,其实就是类的真正的构造函数。Kotlin多个init代码块都是按照顺序拷贝进了字节码的init初始化块中,可以理解为它们是构造函数的组成部分。

Java和kotlin成员变量的初始化都是放到字节码的init代码块中,也就是在构造函数中执行的。

到此这篇关于Kotlin字节码层探究构造函数与成员变量和init代码块执行顺序的文章就介绍到这了,更多相关Kotlin构造函数内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

时间: 2022-11-13

Kotlin lateinit与by lazy案例详解

lateinit 和 lazy 是 Kotlin 中的两种不同的延迟初始化的实现 lateinit 只用于变量 var,而 lazy 只用于常量 val lazy 应用于单例模式(if-null-then-init-else-return),而且当且仅当变量被第一次调用的时候,委托方法才会执行. lazy()是接受一个 lambda 并返回一个 Lazy <T> 实例的函数,返回的实例可以作为实现延迟属性的委托: 第一次调用 get() 会执行已传递给 lazy() 的 lambda 表达式并

Kotlin如何安全访问lateinit变量的实现

Kotlin设计之初就是不允许非null变量在声明期间不进行初始化的,为了解决这个问题,Kotlin lateinit 允许我们先声明一个变量,然后在程序执行周期的将来某个时候将其初始化,让编译检查时不会 因为属性变量未被初始化而报错.如果未初始化将导致以下异常: kotlin.UninitializedPropertyAccessException: lateinit property mList has not been initialized 所以我们在 Kotlin 1.2及更高版本上,

python访问系统环境变量的方法

本文实例讲述了python访问系统环境变量的方法.分享给大家供大家参考.具体如下: #-------------------------------- # Name: enviroment_variables.py # Author: Kevin Harris # Last Modified: 02/13/04 # Description: This Python script demonstrates # how to acces enviroment variables. #--------

java使用反射访问成员变量的值示例

本文实例讲述了java使用反射访问成员变量的值.分享给大家供大家参考,具体如下: 一 代码 import java.lang.reflect.*; class Person { private String name; private int age; public String toString() { return "Person[name:" + name + " , age:" + age + " ]"; } } public class

java 继承访问成员变量代码实例

这篇文章主要介绍了java 继承访问成员变量代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 package java09; //创建父类 public class Fu { int numFu = 10; int num =100; public void methodFu(){ System.out.println(num); } } package java09; //创建子类 public class Zi extends Fu

JavaScript闭包函数访问外部变量的方法

闭包是指有权访问另一个函数作用域中的变量的函数,但作用域的配置机制有一个需要注意的地方,即闭包只能取得包含函数中任何变量的最后一个值. 如以下案例: function create(){     var arr = new Array();        for (var i=0; i<10; i++){         arr[i] = function(){             return i;         };      }       return arr; }   var c

六、访问CGI变量

6.1 CGI变量概述 如果你是从传统的CGI编程转而学习Java Servlet,或许已经习惯了"CGI变量"这一概念.CGI变量汇集了各种有关请求的信息: 部分来自HTTP请求命令和请求头,例如Content-Length头: 部分来自Socket本身,例如主机的名字和IP地址: 也有部分与服务器安装配置有关,例如URL到实际路径的映射. 6.2 标准CGI变量的Servlet等价表示 下表假定request对象是提供给doGet和doPost方法的HttpServletReque

java1.5中访问环境变量

如: 复制代码 代码如下: public class EnvTest {   public static void main(String args[]) {     System.out.println(System.getenv(args[0]));   } } 运行结果: C:\java>java    EnvTest OS Windows_NT 又如: 复制代码 代码如下: import java.util.Map; public class EnvDump { public stati

Python中设置变量访问权限的方法

在Class内部,可以有属性和方法,而外部代码可以通过直接调用实例变量的方法来操作数据,这样,就隐藏了内部的复杂逻辑. 但是,从前面Student类的定义来看,外部代码还是可以自由地修改一个实例的name.score属性: >>> bart = Student('Bart Simpson', 98) >>> bart.score 98 >>> bart.score = 59 >>> bart.score 59 如果要让内部属性不被外部

Java的访问修饰符与变量的作用域讲解

Java访问修饰符(访问控制符) Java 通过修饰符来控制类.属性和方法的访问权限和其他功能,通常放在语句的最前端.例如: public class className { // body of class } private boolean myFlag; static final double weeks = 9.5; protected static final int BOXWIDTH = 42; public static void main(String[] arguments)

C语言中结构体偏移及结构体成员变量访问方式的问题讨论

c语言结构体偏移 示例1 我们先来定义一下需求: 已知结构体类型定义如下: struct node_t{ char a; int b; int c; }; 且结构体1Byte对齐 #pragma pack(1) 求: 结构体struct node_t中成员变量c的偏移. 注:这里的偏移量指的是相对于结构体起始位置的偏移量. 看到这个问题的时候,我相信不同的人脑中浮现的解决方法可能会有所差异,下面我们分析以下几种可能的解法: 方法1 如果你对c语言的库函数比较熟悉的话,那么你第一个想到的肯定是of