如何强制类初始化? [英] How to force a class to be initialised?
问题描述
这是最好的和最干净的方法是什么?具体来说,我需要一个静态初始化块中的一些代码来运行在该类中,但我想让它尽可能的清晰。
正在加载!=初始化。
您希望初始化类(这是在执行静态块时执行的) >
摘录自 Java语言规范说:
类或接口类型T将在第一个发生以下任一情况:
- T是一个类,创建一个T实例。
- T是一个类,由T声明的静态方法被调用。
- 分配由T声明的静态字段。
- 使用由T声明的静态字段,并且该字段不是常量变量(§4.12.4)。
- T是顶级类和assert语句嵌套在T中。
在类Class和package java.lang.reflect中调用某些反射方法也会导致类或接口初始化。
Doh,anovstrup,已经说过:只需要一个空的静态函数调用 init
。一定要记录这个好...我个人看不到任何用例在良好的代码的上下文中。
What is the best and cleanest way to do this? Specifically, I need some code in a static initializer block to run in that class, but I'd like to make this as clean-looking as possible.
Loading != Initialization.
You want your class to be initialized (this is when static blocks executed, among other things).
An excerpt from the Java Language Specification says:
A class or interface type T will be initialized immediately before the first occurrence of >any one of the following:
- T is a class and an instance of T is created.
- T is a class and a static method declared by T is invoked.
- A static field declared by T is assigned.
- A static field declared by T is used and the field is not a constant variable (§4.12.4).
- T is a top-level class, and an assert statement (§14.10) lexically nested within T is executed.
Invocation of certain reflective methods in class Class and in package java.lang.reflect also causes class or interface initialization. A class or interface will not be initialized under any other circumstance.
Doh, anovstrup, already said it: Just make an empty static function called init
. Be sure to document that well... I personally can't see any use case for this in the context of well formed code though.
这篇关于如何强制类初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!