静态块执行时间
静态块里的代码不一定是第一次被加载时执行,
确切的说应该是第一次实例化的时候执行~
因为他的执行和类的加载方式有关:
看看下面的:
1,测试类:
package com.daniel.test;
public class TestStatic {
static{
System.out.println("执行静态块!");
}
public void print(){
System.out.println("执行TestStatic.print()!");
}
}
2,主类:
package com.daniel.test;
public class StaticTest {
public static void main(String[] args) throws Exception {
StaticTest st = new StaticTest();
System.out.println("准备加载com.daniel.test.TestStatic...");
Class clazz = st.getClass().getClassLoader().loadClass("com.daniel.test.TestStatic");
System.out.println("加载com.daniel.test.TestStatic成功!");
System.out.println("准备实例化com.daniel.test.TestStatic...");
TestStatic ts = (TestStatic)clazz.newInstance();
System.out.println("实例化com.daniel.test.TestStatic成功!");
ts.print();
}
}
3,执行结果:
准备加载com.daniel.test.TestStatic...
加载com.daniel.test.TestStatic成功!
准备实例化com.daniel.test.TestStatic...
执行静态块!
实例化com.daniel.test.TestStatic成功!
执行TestStatic.print()!
从结果很明显看出,静态块的执行是类第一次实例化的时候进行的~~~~~
而 不是 大家常说的第一次加载类的时候执行的!!!!!