static块在什么时候执行? 1)当调用forName(String)载入class时执行,如果调用ClassLoader.loadClass并不会执行.forName(String,false,ClassLoader)时也不会执行. 2)如果载入Class时没有执行static块则在第一次实例化时执行.比如new ,Class.newInstance()操作 3)static块仅执行一次这是我在一篇文章中看到的一段话,看了之后我又有了很多不明白的地方,找我原先的理解静态变量和静态初始化快不是在类被加载到内存的时候就初始化的吗!就是说用forname(String)载入是执行和调用ClassLoader.loadClass并不会执行,还有第二点也不是很明白,大家帮我看看,有明白的帮我解释解释谢谢了
定义一个类含有static块.public class Static {
static{
System.out.println("This is a static block in TestStatic class.");
}
public int a = 10;
}测试用例1:
Static s1 = new Static();
Static s2 = new Static();
输出语句只有一次, 说明只执行一次.
测试用例2:
Class.forName("test.Static");测试语句输出, 说明class.forName就已经加载了该class. jdk中有句话是这么说的:A call to forName("X") causes the class named X to be initialized. class.forName将会初始化一个Class对象.jdk还说:
Class.forName("Foo")
is equivalent to:
Class.forName("Foo", true, this.getClass().getClassLoader()), 中间的true指明了要初始化.
测试用例3:
Thread.currentThread().getContextClassLoader().loadClass("tset.Static"); 测试语句没有输出.
事实上classLoader.loadClass()不会初始化一个class对象.
public static void main(String[] args) {
try {
Class.forName("TestStatic", false, Test.class.getClassLoader());//加载而不初始化
System.out.println("static initialize");
TestStatic test = new TestStatic(); //在这里执行静态初始化
} catch (ClassNotFoundException ex) {
}
}
}
class TestStatic{
static{
System.out.println("Hello World");
}
}
来看加载的类的顺序,以及初始化的 执行情况。
先父类静态语句快-->子类静态语句块-->父类语句快-->子类语句块-->父类构造-->子类构造
楼主自己写几个例子测试一下吧!
[code]
public class thread130 {
static Record r=new Record();
static{
System.out.println("static");
}
public static void main(String[] args) throws Exception{
System.out.println("main");
}
public thread130() {
System.out.println("=thread130");
}
}class Record{
{
System.out.println("helo");
thread130 t=new thread130();
}
public Record() {
System.out.println("hRecordlo");
}
}
[/code]
static Record r=new Record();
static{
System.out.println("static");
}
public static void main(String[] args) throws Exception{
System.out.println("main");
}
public thread130() {
System.out.println("=thread130");
}
}class Record{
{
System.out.println("helo");
thread130 t=new thread130();
}
public Record() {
System.out.println("hRecordlo");
}
}
[/code]
public class thread130 {
static Record r=new Record();
static{
System.out.println("static");
}
public static void main(String[] args) throws Exception{
System.out.println("main");
}
public thread130() {
System.out.println("=thread130");
}
}class Record{
{
System.out.println("helo");
thread130 t=new thread130();
}
public Record() {
System.out.println("hRecordlo");
}
}[
先父类静态语句快-->子类静态语句块-->父类语句快-->父类构造-->子类语句块-->子类构造
boolean initialize,
ClassLoader loader)
throws ClassNotFoundException这个是Class.forName静态方法,当指定initialize参数为true的时候,static块是在类加载的时候执行
当指定initialize参数为false的时侯,static块是在类实例化的时候才执行
楼主可以自己谢谢测试程序
先父类静态语句快-->子类静态语句块-->父类语句快-->父类构造-->子类语句块-->子类构造 这个正确!
public class Test8 {
static{
try {
DB_CLASS = Class.forName("...");
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
} public static final Class DB_CLASS;
}