java static{}块
java中static{}块只有在类加载是才会被调用。
这说明:static只有可能被调用一次。
原因:首先理解什么是类加载,区分类加载和申明对象的区别。
public class StaticTest { static { int x = 5; System.out.print(x + "\n"); } public StaticTest() { System.out.print("构造方法" + "\n"); } public static void myMethod() { int x = 0; int y = 0; y = x++ + ++x; System.out.print(x + "and" + y + "\n"); } public static void main(String[] args) { // TODO Auto-generated method stub StaticTest aa = new StaticTest(); StaticTest bb = new StaticTest();
Class<?> T = null;
try {
T = Class.forName("com.fnst.demo.StaticTest");
//使用Class.forName()来加载类,并指定ClassLoader,初始化时不执行静态块
//Class.forName("com.fnst.demo.StaticTest", false, loader);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
StaticTest.myMethod();
}
}
执行结果是:
5 构造方法 构造方法 2and2
首次申明对象时需要加载StaticTest 类,申明aa,bb时在内存中开辟这两个对象的空间。