CodeGym /课程 /Java 核心 /正在加载类,静态数据…

正在加载类,静态数据…

Java 核心
第 5 级, 课程 7
可用

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

“不错,金。”

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

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");
}
}
4
任务
Java 核心, 第 5 级, 课程 7
已锁定
Code entry
Your attention, please! Now recruiting code entry personnel for CodeGym. Turn up your focus, let your fingers relax, read the code, and then... type it into the appropriate box. Code entry is far from a useless exercise, though it might seem so at first glance: it allows a beginner to get used to and remember syntax (modern IDEs seldom make this possible).

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

“嗯,我明白了。”

“非常好。”

评论 (2)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Niko 级别 41,Wuhan,China
21 三月 2022
初始化类时就会为静态变量赋值,这发生在创建对象之前。此时如果需要执行复杂代码为静态变量赋初值,代码应放在静态初始化中。”初始化类涉及为所有静态变量赋值并调用所有静态初始化块”。
null 级别 17,Chengdu
15 三月 2021
如果不需要,Java 机器就不会加载。一旦在代码中的某个地方调用了某个类,Java 机器就会检查是否已加载该类。如果不加载,机器会加载并初始化。 感觉翻译是“如果没有加载”,机器会加载并初始化。