Class.forName("package.class")的意義
java里面任何class都要裝載在虛擬機上才能運行。Class.forName(xxx.xx.xx)就是裝載類用的(和new 不一樣,要分清楚),裝載后jvm將執(zhí)行類中的靜態(tài)代碼。
至于什么時候用,可以考慮一下這個問題,給你一個字符串變量,它代表一個類的包名和類名,你怎么實例化它?只有用提到的這個方法了,不過要再加一點。
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驅動中,有一塊靜態(tài)代碼,也叫靜態(tài)初始化塊,它執(zhí)行的時間是當class調入到內(nèi)存中就執(zhí)行(你可以想像成,當類調用到內(nèi)存后就執(zhí)行一個方法)。所以很多人把jdbc driver調入到內(nèi)存中,再實例化對象是沒有意義的。