1.虚拟机启动时,指定一个要执行的主类,虚拟机会优先初始化这个(带main方法的)主类
public class TestMode {
static {
System.out.println("会触发类的初始化");
}
public static void main(String[] args) {
}
}
2.通过数组定义来引用类,不会触发类的初始化
class Test {
static {
System.out.println("通过数组定义来引用类,不会触发类的初始化");
}
}
public class TestMode {
private static Test test1;
private static Test test;
public static void main(String[] args) {
Test[] testModes = new Test[] { test, test1 };
for (int m = 0; m < testModes.length; m++) {
System.out.println(testModes[m]);
}
}
}
3.访问一个类的非final静态字段或static方法时(访问fianl字段时直接从该类常量池中拿取,并不会造成初始化)
class test {
static int a = 1;
static {
System.out.println("hello");
}
}
public class newtestdemo_1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(test.a);
}
}
结果为 hello 1
4.遇到new、getstatic、putstatic或invokestatic这四条字节码指令时
class test {
static {
System.out.println("hello");
}
}
public class newtestdemo_1 {
public static void main(String[] args) {
new test();
}
}
5.使用反射机制等
class test {
static {
System.out.println("hello");
}
}
public class newtestdemo_1 {
public static void main(String[] args) throws ClassNotFoundException {
Class.forName("caogao1.test");
}
}
6.当初始化一个类的时候,如果发现其父类还没有进行过初始化,则需要先触发其父类的初始化
class test01 {
static {
System.out.println("hello");
}
}
class test02 extends test01 {
static {
System.out.println("world");
}
}
public class newtestdemo_1 {
public static void main(String[] args) throws ClassNotFoundException {
new test02();
}
}