我们知道java中的静态 block 是在编译时解析的,而不是在运行时解析的。因此,我们再次知道静态内部类是在第一次调用嵌套类期间实例化的。 现在假设嵌套类有一个静态 block 。那么,在这种情况下,我们是否可以说,当第一次尝试访问嵌套类时,嵌套类内的静态 block 将被解析? 示例代码:
public class A
{
public static class B
{
static A a;
static
{
a=new A();
}
public static A getA()
{
return a;
}
}
}
现在我正在访问: A a= A.b.getInstance(); 我希望此时只有 B 中的静态 block 会被执行,而不是在此之前。
最佳答案
这应该可以回答您的问题:
public class Test {
public Test() {
System.out.println("Test instantiated");
}
public static class Inner {
static {
System.out.println("Static block executed");
}
public Inner() {
System.out.println("Test.Inner instantiated");
}
}
}
调用时:
Test test = new Test();
Test.Inner inner = new Test.Inner();
我们得到:
Test instantiated
Static block executed
Test.Inner instantiated
关于java - 静态内部类中的静态 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23997959/