- public class Office{
- public static void main(Stringp[] args)
- {
- Office office = new Office();
- System.out.println("Start to load class"); //开始加载类
- Class c = Class.forName(args[0], false, office.getClass().getClassLoader());// 从输入参数中获得要初始化的类
- System.out.println("Start to instantiate class"); //开始初始化类
- Object word = c.newInstance();
- word.start();
- }
- }
- //Word.java
- public class Word{
- static{
- System.out.println("Word initialize in static block");
- }
- public void print(){
- System.out.println("Word is used");
- }
- }
- <DIV style="TEXT-ALIGN: left; WIDOWS: 2; TEXT-TRANSFORM: none; BACKGROUND-COLOR: rgb(204,206,208); TEXT-INDENT: 0px; LETTER-SPACING: normal; FONT: 14px/25px Arial, Helvetica, simsun, u5b8bu4f53; WHITE-SPACE: normal; ORPHANS: 2; COLOR: rgb(51,51,51); WORD-SPACING: 0px; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px">输出结果应该是:
- <SPAN style="LINE-HEIGHT: 25px; FONT-FAMILY: monospace; WHITE-SPACE: pre">Start to load class</SPAN></DIV>
- <DIV style="TEXT-ALIGN: left; WIDOWS: 2; TEXT-TRANSFORM: none; BACKGROUND-COLOR: rgb(204,206,208); TEXT-INDENT: 0px; LETTER-SPACING: normal; FONT: 14px/25px Arial, Helvetica, simsun, u5b8bu4f53; WHITE-SPACE: normal; ORPHANS: 2; COLOR: rgb(51,51,51); WORD-SPACING: 0px; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px"><SPAN style="LINE-HEIGHT: 25px; FONT-FAMILY: monospace; WHITE-SPACE: pre"><FONT style="LINE-HEIGHT: 23px" size=3>Start to instantiate class</FONT></SPAN></DIV>
- <DIV style="TEXT-ALIGN: left; WIDOWS: 2; TEXT-TRANSFORM: none; BACKGROUND-COLOR: rgb(204,206,208); TEXT-INDENT: 0px; LETTER-SPACING: normal; FONT: 14px/25px Arial, Helvetica, simsun, u5b8bu4f53; WHITE-SPACE: normal; ORPHANS: 2; COLOR: rgb(51,51,51); WORD-SPACING: 0px; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px"><SPAN style="LINE-HEIGHT: 25px; FONT-FAMILY: monospace; WHITE-SPACE: pre">Word initialize in static block<SPAN style="TEXT-ALIGN: left; WIDOWS: 2; TEXT-TRANSFORM: none; BACKGROUND-COLOR: rgb(204,206,208); TEXT-INDENT: 0px; LETTER-SPACING: normal; DISPLAY: inline !important; FONT: 14px/25px monospace; WHITE-SPACE: pre; ORPHANS: 2; FLOAT: none; COLOR: rgb(51,51,51); WORD-SPACING: 0px; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px">Word is used
- 从中可以看出,类加载的时候并没有调用Word类的静态初始化块,而是在实例化的时候调用初始化块的。 所以最后关于类静态初始化块被调用时间的更准备的表述应该为: 类的静态初始化块是在类实例化和加载的时候被调用和初始化的.</SPAN>
- </SPAN></DIV>
复制代码 |