“何时加载类”是什么意思?其实是什么意思? [英] What does "When a Class is loaded" actually mean?

查看:94
本文介绍了“何时加载类”是什么意思?其实是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据说在Java中的静态块在加载该类时仅运行一次。但这实际上是什么意思? JVM(Java虚拟机)在什么时候加载类?

It is said that static blocks in java run only once when that class is loaded. But what does it actually mean? At which point is a class loaded by JVM (Java Virtual Machine)?

当调用该类中的main方法时是吗?并且是在main方法开始执行时是否也加载了同一类的所有超类吗?

Is it when the main method in that class is called? And is it that all the super-classes of the same class are also loaded when the main method starts execution?

考虑到A扩展了B且B扩展了C。静态块。如果A具有main方法,那么执行静态块的顺序是什么?

Consider that A extends B and B extends C. All have static blocks. If A has the main method, then what will be the sequence of execution of static blocks?

推荐答案

这在< JLS的href = http://java.sun.com/docs/books/jls/second_edition/html/execution.doc.html rel = noreferrer>执行部分。即:


类的初始化包括执行其静态初始化程序和该类中声明的静态字段的初始化程序。接口的初始化包括对接口中声明的字段执行初始化程序。

在初始化类之前,必须先对其直接超类进行初始化,但是需要由该类实现的接口尚未初始化。同样,在初始化接口之前无需初始化接口的超级接口。

Initialization of a class consists of executing its static initializers and the initializers for static fields declared in the class. Initialization of an interface consists of executing the initializers for fields declared in the interface.
Before a class is initialized, its direct superclass must be initialized, but interfaces implemented by the class need not be initialized. Similarly, the superinterfaces of an interface need not be initialized before the interface is initialized.

因此,在您的示例中,首先运行最高类( C ),然后运行 B 的类,然后是派生最多的类。

So in your example, the static block of the "topmost" class (C) runs first, then that of B, then the most-derived one.

请参阅该文档,详细了解装入类的所有步骤。

See that documentation for a detailed description of all the steps that go into loading a class.

(类在首次使用时会被加载。)

(Classes get loaded when they are first actively used.)

这篇关于“何时加载类”是什么意思?其实是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆