如何在 Java 中显式调用静态初始化程序?
How to explicitly call the static initializer in Java?
所以,作为示例,我有这个 JNI 代码:
/** This literally does nothing. It's purpose is to call the static initializer early to detect if we have issues before loading. */
public static void nothing() {
}
static {
// should be loaded by CLib
if (CLib.hasGNUTLS() == 1) {
globalinit();
}
}
我发现自己实际上是在创建一个名为 "nothing" 的函数,以便在必要时提前调用它,但我也希望在它被较早引用或我们不调用 nothing()
时调用它。现在,我可以做一些涉及检查布尔值的令人讨厌的逻辑,但是你会进入线程安全,等等。我想你可以,但它并不漂亮。有没有办法显式调用 GNUTLS.<clinit>();
?
静态初始化器总是在你的方法之前运行,因为初始化器运行是在class被初始化的时候。 JLS-8.7. Static Initializers 说(部分)
A static initializer declared in a class is executed when the class is initialized (§12.4.2). Together with any field initializers for class variables (§8.3.2), static initializers may be used to initialize the class variables of the class.
而且,您无法显式调用任何初始化程序(static
或 ,否则 )。但是,Class.forName(String)
表示(部分)
A call to forName("X")
causes the class named X
to be initialized.
所以,作为示例,我有这个 JNI 代码:
/** This literally does nothing. It's purpose is to call the static initializer early to detect if we have issues before loading. */
public static void nothing() {
}
static {
// should be loaded by CLib
if (CLib.hasGNUTLS() == 1) {
globalinit();
}
}
我发现自己实际上是在创建一个名为 "nothing" 的函数,以便在必要时提前调用它,但我也希望在它被较早引用或我们不调用 nothing()
时调用它。现在,我可以做一些涉及检查布尔值的令人讨厌的逻辑,但是你会进入线程安全,等等。我想你可以,但它并不漂亮。有没有办法显式调用 GNUTLS.<clinit>();
?
静态初始化器总是在你的方法之前运行,因为初始化器运行是在class被初始化的时候。 JLS-8.7. Static Initializers 说(部分)
A static initializer declared in a class is executed when the class is initialized (§12.4.2). Together with any field initializers for class variables (§8.3.2), static initializers may be used to initialize the class variables of the class.
而且,您无法显式调用任何初始化程序(static
或 ,否则 )。但是,Class.forName(String)
表示(部分)
A call to
forName("X")
causes the class namedX
to be initialized.