“你好,阿米戈!听说里希告诉了你一些新颖而有趣的事情?!”

“不错,金。”

“我的话题也一样有趣。我想告诉你内存中如何加载类。”

Java 中的类是磁盘上包含字节码(即已编译的 Java 代码)的文件。

“是的,我记得。”

如果不需要,Java 机器就不会加载。一旦在代码中的某个地方调用了某个类,Java 机器就会检查是否已加载该类。如果不加载,机器会加载并初始化。

初始化类涉及为所有静态变量赋值并调用所有静态初始化块。

“这似乎类似于在对象上调用构造方法。但是,什么是静态初始化块?”

“如果你要执行复杂的代码(例如,从文件中加载内容)来初始化对象,我们可以在构造方法中完成。不过静态变量可不行。既然仍需要,你可以在类中添加静态初始化块。它们基本上等同于静态构造方法。”

看起来如下所示:

代码 实际发生的情况如下
class Cat
{
public static int catCount = 0 ;
public static String namePrefix;

static
{
Properties p = new Properties();
p.loadFromFile("cat.properties");
namePrefix = p.get("name-prefix");
}

public static int maxCatCount = 50;

static
{
Properties p = new Properties();
p.loadFromFile("max.properties");
if (p.get("cat-max") != null)
maxCatCount = p.getInt("cat-max");
}

}


class Cat
{
public static int catCount;
public static String namePrefix;
public static int maxCatCount;

//Static constructors aren't allowed in Java,
//but if they were, everything
//would look like this
public static Cat()
{
catCount = 0;

Properties p = new Properties();
p.loadFromFile("cat.properties");
namePrefix = p.get("name-prefix");

maxCatCount = 50;

Properties p2 = new Properties();
p2.loadFromFile("max.properties");
if (p2.get("cat-max")!=null)
maxCatCount = p2.getInt("cat-max");
}
}

这很像调用构造方法时发生的事情。我甚至将其编写为(不存在的)静态构造方法。

“嗯,我明白了。”

“非常好。”