【发布时间】:2016-01-25 11:09:30
【问题描述】:
我的目标是让几个类在程序开始时运行一段代码。假设可以一时兴起将类添加到项目中,而在main 开头调用的静态函数将是不切实际的。
我试图将初始化例程放在这些类的静态块中,它几乎按预期工作,但不完全。只有在该类中的其他内容被调用后,这些块才会被调用。这可以通过下面的代码来证明:
Test.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()");
}
}
Another2.java
public class Another2
{
static
{
System.out.println("Another2.static{}");
}
public Another2()
{
System.out.println("Another2.Another2()");
}
}
输出是:
Begin
Another.static{}
Another.Another()
可以看出Another2被假定为根本不存在。
问题是:如果所有类都有静态块,是否有可能“踢”它们执行它们的静态块?
【问题讨论】:
标签: java static-block