Java代码:
public
class StaticDemo {
public static String info ;
private String other ;
static {
info = "静态语句块能操纵静态的对象";
//other = "无法操纵非static对象";
System.out.println(" == StaticDemo 被加载到
JVM == ");
}
public StaticDemo(){
System.out.println(" StaticDemo 被实例化了。");
}
}
Java代码:
public class StaticTest {
public static void main(String[] args) {
// 加载到JVM中,默认的方式
try {
// 等效于Class.forName("StaticDemo");
Class.forName("StaticDemo", true, StaticTest.class.getClassLoader());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// 加载的JVM时,info被赋值了
System.out.println("info对象 ==> "+StaticDemo.info);
// 实例化对象,注意此时Static语句块中的内容不再出现
StaticDemo obj1 = new StaticDemo();
StaticDemo obj2 = new StaticDemo();
}
}
执行结果:
---------------
== StaticDemo 被加载到JVM ==
info对象 ==> 静态语句块能操纵静态的对象
StaticDemo 被实例化了。
StaticDemo 被实例化了。
---------------
-------------------------------------------------
import java.util.ArrayList;
import java.util.List;
public class Test {
private static List list = new ArrayList() {
{
add(new Object());
// ...
}
};
// 除了这样初始化list之外,还可以如下:
private static List list2;
static {
list2 = new ArrayList();
list2.add(new Object());
// ...
}
// private static A a = new A(); 这样写就不允许了
private static A a;
static {
try {
a = new A();
} catch (Exception e) {
e.printStackTrace();
}
}
static class A {
public A() throws Exception {
}
}
}
--------------------------
package com.test;
class Test {
public static int X = 100;
public final static int Y = 200;
public Test() {
System.out.println("Test
构造函数执行");
}
static {
System.out.println("static语句块执行");
}
public static void display() {
System.out.println("
静态方法被执行");
}
public void display_1() {
System.out.println("实例方法被执行");
}
}
public class StaticBlockTest {
public static void main(String args[]) {
try {
Class.forName("com.test.Test");
Class.forName("com.test.Test");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
----------
执行结果:
static语句块执行
----------