Class.forName("package.class")的意義

          java里面任何class都要裝載在虛擬機(jī)上才能運(yùn)行。Class.forName(xxx.xx.xx)就是裝載類用的(和new 不一樣,要分清楚),裝載后jvm將執(zhí)行類中的靜態(tài)代碼。

          至于什么時候用,可以考慮一下這個問題,給你一個字符串變量,它代表一個類的包名和類名,你怎么實(shí)例化它?只有用提到的這個方法了,不過要再加一點(diǎn)。
          A a = (A)Class.forName("pacage.A").newInstance();
          這和
          A a = new A();
          是一樣的效果。

          有的jdbc連接數(shù)據(jù)庫的寫法里是Class.forName(xxx.xx.xx);而有一些是Class.forName(xxx.xx.xx).newInstance(),為什么會有這兩種寫法呢?

          Class.forName(xxx.xx.xx) 返回的是一個類Class。
          Class.forName(xxx.xx.xx).newInstance() 是創(chuàng)建一個對象,返回的是Object。
          Class.forName(xxx.xx.xx)的作用是要求JVM查找并加載指定的類,也就是說JVM會執(zhí)行該類的靜態(tài)代碼段。

          在JDBC規(guī)范中明確要求這個Driver類必須向DriverManager注冊自己,即任何一個JDBC Driver的Driver類的代碼都必須類似如下:
          public class MyJDBCDriver implements Driver {
          static {
          DriverManager.registerDriver(new MyJDBCDriver());
          }
          }

          所以我們在使用JDBC時只需要Class.forName(XXX.XXX);就可以了

          we just want to load the driver to jvm only, but not need to user the instance of driver, so call Class.forName(xxx.xx.xx) is enough, if you call Class.forName(xxx.xx.xx).newInstance(), the result will same as calling Class.forName(xxx.xx.xx), because Class.forName(xxx.xx.xx).newInstance() will load driver first, and then create instance, but the instacne you will never use in usual, so you need not to create it.

          在JDBC驅(qū)動中,有一塊靜態(tài)代碼,也叫靜態(tài)初始化塊,它執(zhí)行的時間是當(dāng)class調(diào)入到內(nèi)存中就執(zhí)行(你可以想像成,當(dāng)類調(diào)用到內(nèi)存后就執(zhí)行一個方法)。所以很多人把jdbc driver調(diào)入到內(nèi)存中,再實(shí)例化對象是沒有意義的。

           

          posted on 2008-06-12 14:51 chenkai 閱讀(281) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導(dǎo)航:
           
          <2008年6月>
          25262728293031
          1234567
          891011121314
          15161718192021
          22232425262728
          293012345

          導(dǎo)航

          統(tǒng)計

          常用鏈接

          留言簿(2)

          隨筆檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 上杭县| 龙山县| 麦盖提县| 巴青县| 花垣县| 虞城县| 巴彦淖尔市| 根河市| 黔江区| 江山市| 江川县| 长白| 大田县| 盱眙县| 宜都市| 济南市| 巩义市| 富锦市| 嘉定区| 丰台区| 玛曲县| 浦北县| 重庆市| 应城市| 信丰县| 白城市| 工布江达县| 旺苍县| 静安区| 镇康县| 黄浦区| 田阳县| 新竹市| 正阳县| 涿州市| 上栗县| 海南省| 靖西县| 瑞丽市| 宜川县| 崇明县|