我的目标是有几个类有一个在程序开始时运行的代码块。假设可以一时兴起将类添加到项目中,并且在main
.
我试图将初始化例程放在这些类的静态块中,它几乎可以按预期工作,但并不完全。只有在该类中的其他内容被调用后,这些块才会被调用。这可以通过下面的代码来证明:
测试.java
public class Test
{
public static void main(String[] args)
{
System.out.println("Begin");
new Another();
}
}
另一个.java
public class Another
{
static
{
System.out.println("Another.static{}");
}
public Another()
{
System.out.println("Another.Another()");
}
}
另一个2.java
public class Another2
{
static
{
System.out.println("Another2.static{}");
}
public Another2()
{
System.out.println("Another2.Another2()");
}
}
输出是:
Begin
Another.static{}
Another.Another()
可以看出,Another2
假设根本不存在。
问题是:是否有可能“踢”所有类来执行它们的静态块(如果它们有它们)?