一、类代码:
package com.example.controller;
public class TestInit {
int i=23;
private int j=5;
public String str="Hello , world!";
}
二、javap -verbose TestInit
Last modified 2022-6-19; size 437 bytes
MD5 checksum 00f45694f7013668d5515641a5da1bbb
Compiled from "TestInit.java"
public class com.example.controller.TestInit
minor version: 0
major version: 52
flags: ACC_PUBLIC, ACC_SUPER
Constant pool:
#1 = Methodref #7.#22 // java/lang/Object."<init>":()V
#2 = Fieldref #6.#23 // com/example/controller/TestInit.i:I
#3 = Fieldref #6.#24 // com/example/controller/TestInit.j:I
#4 = String #25 // Hello , world!
#5 = Fieldref #6.#26 // com/example/controller/TestInit.str:Ljava/lang/String;
#6 = Class #27 // com/example/controller/TestInit
#7 = Class #28 // java/lang/Object
#8 = Utf8 i
#9 = Utf8 I
#10 = Utf8 j
#11 = Utf8 str
#12 = Utf8 Ljava/lang/String;
#13 = Utf8 <init>
#14 = Utf8 ()V
#15 = Utf8 Code
#16 = Utf8 LineNumberTable
#17 = Utf8 LocalVariableTable
#18 = Utf8 this
#19 = Utf8 Lcom/example/controller/TestInit;
#20 = Utf8 SourceFile
#21 = Utf8 TestInit.java
#22 = NameAndType #13:#14 // "<init>":()V
#23 = NameAndType #8:#9 // i:I
#24 = NameAndType #10:#9 // j:I
#25 = Utf8 Hello , world!
#26 = NameAndType #11:#12 // str:Ljava/lang/String;
#27 = Utf8 com/example/controller/TestInit
#28 = Utf8 java/lang/Object
{
int i;
descriptor: I
flags:
public java.lang.String str;
descriptor: Ljava/lang/String;
flags: ACC_PUBLIC
public com.example.controller.TestInit();
descriptor: ()V
flags: ACC_PUBLIC
Code:
stack=2, locals=1, args_size=1
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: aload_0
5: bipush 23
7: putfield #2 // Field i:I
10: aload_0
11: iconst_5
12: putfield #3 // Field j:I
15: aload_0
16: ldc #4 // String Hello , world!
18: putfield #5 // Field str:Ljava/lang/String;
21: return
LineNumberTable:
line 3: 0
line 4: 4
line 5: 10
line 6: 15
LocalVariableTable:
Start Length Slot Name Signature
0 22 0 this Lcom/example/controller/TestInit;
}
SourceFile: "TestInit.java"
三、结论:
可以在生成的构造方法public com.example.controller.TestInit();的字节码中看到给类变量赋值的指令:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: aload_0
5: bipush 23
7: putfield #2 // Field i:I
10: aload_0
11: iconst_5
12: putfield #3 // Field j:I
15: aload_0
16: ldc #4 // String Hello , world!
18: putfield #5 // Field str:Ljava/lang/String;
21: return
如果有多个构造方法,每个方法里都会包含上述初始化指令