One o'clock eye
1 the following six kinds of ways, the system will initialize the class or interface.
-
Create an instance of the class. Create an instance of a class includes the use of the new operator to create an instance to create an instance by reflection, to create an instance by way deserialized.
-
Call the static method of a class.
-
Access to a class or static properties of the interface, or assignment for the static properties.
-
To force the creation of a class or an interface corresponding to the object using java.lang.Class reflection mode. For example the code: Class.forName ( "Person").
-
Subclass initialization of a class, subclass initialized when a class, all the parent of the child class will be initialized.
-
Direct use java.exe command to run a master class, when you run a master class, the program will first initialize the main class.
2 final type static property, if the property can get property values at compile time can be considered as the property may be compile-time constant. When a program uses compile-time constants, the system will think this is a passive use of the class, so it will not lead to initialize the class.
Two combat
Code 1
class MyTest
{
static
{
System.out.println("静态初始化块...");
}
// 使用一个字符串直接量为static final的类变量赋值
static final String compileConstant = "疯狂Java讲义";
}
public class CompileConstantTest
{
public static void main(String[] args)
{
// 访问、输出MyTest中的compileConstant类变量
System.out.println(MyTest.compileConstant); // ①
}
}
2 runs
Crazy Java handouts
3 Description
Using a modified static final class, and its value can be determined at compile time down, then do not initialize the class.
Three combat
Code 1
class Tester
{
static
{
System.out.println("Tester类的静态初始化块...");
}
}
public class ClassLoaderTest
{
public static void main(String[] args)
throws ClassNotFoundException
{
ClassLoader cl = ClassLoader.getSystemClassLoader();
// 下面语句仅仅是加载Tester类
cl.loadClass("Tester");
System.out.println("系统加载Tester类");
// 下面语句才会初始化Tester类
Class.forName("Tester");
}
}
2 runs
系统加载Tester类
Tester类的静态初始化块...
3 Description
loadClass loads only the class, and it does not perform the initialization of the class.
forName lead to arbitrary initialization class.