静态初始化块的使用
我知道静态初始化块是如何工作的。
谁能告诉我它的一些典型用途。
I know how a static init block works.
Can anyone please tell me some typical uses of it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我知道静态初始化块是如何工作的。
谁能告诉我它的一些典型用途。
I know how a static init block works.
Can anyone please tell me some typical uses of it.
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(7)
当您想在一处初始化一个或多个静态变量时,
它很有用,因为您可以应用异常处理,而这是内联初始化所无法实现的。
例如:
可以用另一个应用程序来初始化
复杂的初始化。例如,如果一项需要多行代码来初始化。假设您有一个配置:
第三种用途是初始化一些外部 API 基础设施。我当前项目中的一个例子:
但是,正如 Mykola Golubyev 指出的那样,静态初始化块会降低代码的可读性,因此请谨慎使用它们。静态方法更透明地完成同样的事情。
When you want to initialize one or more static variables in one place
It is useful, because you can apply exception handling, which is not possible with the in-line initialization.
For example:
can be initialized with
Another application is complex initialization. For example, if an item requires more than one line of code to be initialized. Let's say you have a configuration:
A third usage is to initialize some external API infrastructure. One example from my current project:
But, as Mykola Golubyev noted, static initialization blocks make code less readable, so use them with caution. static methods do the same thing more transparently.
只是尽量避免使用静态初始化块。相反,您可以使用私有静态初始化函数,这将使您的代码更加干净。
我将参考@Bozho 的例子。
不要
使用代替
或
Just try to avoid use of static initialization block. Instead you can use private static initialization functions which will make your code more clean.
I will refer to @Bozho for examples.
Do not do
Use instead
or
它们通常与 JNI 代码结合使用,以确保加载所需的本机库:
They're often used in conjunction with JNI code to ensure that the required native library is loaded:
字段,如 Map、List、Set 等
field, like Map, List, Set, etc
JDBC 驱动程序是一个流行的示例
为什么需要
Class.forName()
将驱动程序加载到内存中。答案很简单。根据 JDBC 规范的规定,所有 JDBCDriver
都有一个静态块,一旦加载Driver
类,就会向DriverManager
注册自己。像这样的事情:因此,当您编写时(例如,使用此处的 MySQL 驱动程序):
类加载器尝试加载并链接 org.gjt.mm.mysql.Driver 类,如果成功,则执行静态初始化块,并且
Driver
将自身注册到DriverManager
。JDBC Driver Is a Popular Example
Why do you need
Class.forName()
to load a driver into memory. The answer is simple. As stipulated in the JDBC specs, all JDBCDriver
have a static block to register themselves withDriverManager
as soon as theDriver
class is loaded. Something like this:So, when you write (for example with the MySQL driver here):
The classloader attempts to load and link the
org.gjt.mm.mysql.Driver
class and, if successful, the static initialization block gets executed and theDriver
registers itself with theDriverManager
.它们可以用来创建 DSL,就像 JMock 所做的那样。例如,要设置将用户保存到数据库的期望:
They can be used to create a DSL, as JMock does. For instance, to set an expectation that a user will be saved to the database: