我的目标是让几个类拥有一个在程序开始时运行的代码块.假设一下,可以随心所欲地将类添加到项目中,并且在开头调用静态函数是不切实际的main.
我试图将初始化例程放在这些类的静态块中,它几乎按预期工作,但并不完全.只有在调用该类中的其他内容后才会调用这些块.这可以通过以下代码证明:
Test.java
public class Test
{
public static void main(String[] args)
{
System.out.println("Begin");
new Another();
}
}
Run Code Online (Sandbox Code Playgroud)
Another.java
public class Another
{
static
{
System.out.println("Another.static{}");
}
public Another()
{
System.out.println("Another.Another()");
}
}
Run Code Online (Sandbox Code Playgroud)
Another2.java
public class Another2
{
static
{
System.out.println("Another2.static{}");
}
public Another2()
{
System.out.println("Another2.Another2()");
}
}
Run Code Online (Sandbox Code Playgroud)
输出是:
Begin
Another.static{}
Another.Another()
Run Code Online (Sandbox Code Playgroud)
可以看出,Another2假设根本不存在.
问题是:是否可以"踢"所有类来执行它们的静态块(如果有的话)?
Aro*_*_dc 10
如果类由ClassLoader加载,则执行静态块.因此,如果迭代所有类并通过类加载器加载它们(无需实例化它们!),每个静态块将执行一次.
在更深层次上,我无法想象你真正需要这种情况的情况.这在某种程度上暗示了错误设计的类结构.