Skip to content

Commit 6840e59

Browse files
committed
[add] add class loading example in jvm module
1 parent 0ebc64a commit 6840e59

File tree

5 files changed

+74
-0
lines changed

5 files changed

+74
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.brianway.learning.java.jvm.classfile;
2+
3+
/**
4+
* Created by brian on 17/3/19.
5+
* 被动使用类字段演示
6+
* 常量在编译阶段会存入调用类的常量池,本质上没有引用调用常量的类,
7+
* 不会触发定义常量的类的初始化
8+
*/
9+
public class ConstClass {
10+
static {
11+
System.out.println("ConsClass init!");
12+
}
13+
14+
public static final String HELLOWORLD = "hello world";
15+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.brianway.learning.java.jvm.classfile;
2+
3+
/**
4+
* Created by brian on 17/3/19.
5+
* 非主动使用类字段演示
6+
* 1. 静态字段只有直接定义这个字段的类才会被初始化
7+
* 2. 通过数组来定义引用类,不会触发类的初始化
8+
* (-XX:+TraceClassLoading,对于 HotSpot 虚拟机可观察到子类的加载)
9+
*/
10+
public class NoInitialization {
11+
public static void main(String[] args) {
12+
System.out.println(SubClass.value);
13+
SubClass[] sca = new SubClass[10];
14+
15+
System.out.println(ConstClass.HELLOWORLD);
16+
}
17+
}
18+
/*
19+
SuperClass init!
20+
123
21+
*/
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package com.brianway.learning.java.jvm.classfile;
2+
3+
/**
4+
* Created by brian on 17/3/15.
5+
* 一段简单的 Java 代码,用于分析字节码
6+
* javap -verbose SimpleClass.java
7+
*/
8+
public class SimpleClass {
9+
private int m;
10+
11+
public int inc() {
12+
return m + 1;
13+
}
14+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package com.brianway.learning.java.jvm.classfile;
2+
3+
/**
4+
* Created by brian on 17/3/19.
5+
*/
6+
public class SubClass extends SuperClass {
7+
static {
8+
System.out.println("SubClass init!");
9+
}
10+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package com.brianway.learning.java.jvm.classfile;
2+
3+
/**
4+
* Created by brian on 17/3/19.
5+
* 被动引用的例子
6+
* 通过子类引用父类的静态字段,不会导致子类初始化
7+
*/
8+
public class SuperClass {
9+
static {
10+
System.out.println("SuperClass init!");
11+
}
12+
13+
public static int value = 123;
14+
}

0 commit comments

Comments
 (0)