Anti

          Anti's BlogJava

          Class.forName()在數(shù)據(jù)庫開發(fā)中的一二

          來自: http://hi.baidu.com/zxf1986518/blog/item/c5fac9cebbc33b32b600c849.html

          終于明白為什么加載數(shù)據(jù)庫驅(qū)動只用Class.forName()了!!困擾了我2個小時!!希望我寫的這個東西對各位有所幫助。 
             
                在Java開發(fā)特別是數(shù)據(jù)庫開發(fā)中,經(jīng)常會用到Class.forName( )這個方法。通過查詢Java Documentation我們會發(fā)現(xiàn)使用Class.forName( )靜態(tài)方法的目的是為了動態(tài)加載類。在加載完成后,一般還要調(diào)用Class下的newInstance( )靜態(tài)方法來實(shí)例化對象以便操作。因此,單單使用Class.forName( )是動態(tài)加載類是沒有用的,其最終目的是為了實(shí)例化對象。 
                這里有必要提一下就是Class下的newInstance()和new有什么區(qū)別?,首先,newInstance( )是一個方法,而new是一個關(guān)鍵字,其次,Class下的newInstance()的使用有局限,因?yàn)樗蓪ο笾荒苷{(diào)用無參的構(gòu)造函數(shù),而使用 new關(guān)鍵字生成對象沒有這個限制。 

                好,到此為止,我們總結(jié)如下: 
               Class.forName("")返回的是類 
               Class.forName("").newInstance()返回的是object 
               有數(shù)據(jù)庫開發(fā)經(jīng)驗(yàn)朋友會發(fā)現(xiàn),為什么在我們加載數(shù)據(jù)庫驅(qū)動包的時候有的卻沒有調(diào)用newInstance( )方法呢?即有的jdbc連接數(shù)據(jù)庫的寫法里是Class.forName(xxx.xx.xx);而有一 些:Class.forName(xxx.xx.xx).newInstance(),為什么會有這兩種寫法呢?
               剛才提到,Class.forName("");的作用是要求JVM查找并加載指定的類,如果在類中有靜態(tài)初始化器的話,JVM必然會執(zhí)行該類的靜態(tài)代碼 段。而在JDBC規(guī)范中明確要求這個Driver類必須向DriverManager注冊自己,即任何一個JDBC Driver的 Driver類的代碼都必須類似如下:
              public class MyJDBCDriver implements Driver {
             static {
               DriverManager.registerDriver(new MyJDBCDriver());
            }
          }
           既然在靜態(tài)初始化器的中已經(jīng)進(jìn)行了注冊,所以我們在使用JDBC時只需要Class.forName(XXX.XXX);就可以了。

          相關(guān) 英文參考文獻(xiàn)如下:
          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.

          posted on 2012-01-18 14:39 Anti 閱讀(148) 評論(0)  編輯  收藏


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


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 西林县| 博爱县| 阳西县| 华安县| 屏边| 衡南县| 漠河县| 安化县| 观塘区| 和龙市| 贵南县| 高雄市| 阿拉善盟| 东平县| 东明县| 岑溪市| 上犹县| 凉城县| 凌海市| 方山县| 渭源县| 江北区| 清新县| 铁力市| 嘉黎县| 吉水县| 论坛| 姚安县| 福清市| 云林县| 天台县| 合川市| 库车县| 孟州市| 璧山县| 筠连县| 两当县| 台湾省| 乌苏市| 东港市| 闽侯县|