?? class.forname的含義.txt
字號(hào):
Class.forName的含義
Class.forName(xxx.xx.xx) 返回的是一個(gè)類, .newInstance() 后才創(chuàng)建一個(gè)對象 Class.forName(xxx.xx.xx);的作用是要求JVM查找并加載指定的類,也就是說JVM會(huì)執(zhí)行該類的靜態(tài)代碼段
Class aClass = Class.forName(xxx.xx.xx);
Object anInstance = aClass.newInstance();
Class.forName("").newInstance()返回的是object
but there is some limit for this method to create instance
that is your class constructor should no contain parameters, and you should cast the instance manually.
Class Driver{
protected static Driver current;
public static Driver getDriver(){
return current;
}
}
Class MyDriver extends Driver{
static{
Driver.current=new MyDriver();
}
MyDriver(){}
}
用時(shí):
Class.forName("MyDriver");
Driver d=Driver.getDriver();
有的jdbc連接數(shù)據(jù)庫的寫法里是Class.forName(xxx.xx.xx);而有一些:Class.forName(xxx.xx.xx).newInstance(),為什么會(huì)有這兩種寫法呢?
Class.forName(xxx.xx.xx) 返回的是一個(gè)類,
.newInstance() 后才創(chuàng)建一個(gè)對象
Class.forName(xxx.xx.xx);的作用是要求JVM查找并加載指定的類,也就是說JVM會(huì)執(zhí)行該類的靜態(tài)代碼段
在JDBC規(guī)范中明確要求這個(gè)Driver類必須向DriverManager注冊自己,即任何一個(gè)JDBC Driver的Driver類的代碼都必須類似如下:
public class MyJDBCDriver implements Driver {
static {
DriverManager.registerDriver(new MyJDBCDriver());
}
}
所以我們在使用JDBC時(shí)只需要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ū)動(dòng)中,有一塊靜態(tài)代碼,也叫靜態(tài)初始化塊,它執(zhí)行的時(shí)間是當(dāng)class調(diào)入到內(nèi)存中就執(zhí)行(你可以想像成,當(dāng)類調(diào)用到內(nèi)存后就執(zhí)行一個(gè)方法)。所以很多人把jdbc driver調(diào)入到內(nèi)存中,再實(shí)例化對象是沒有意義的。
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -