600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > Class.forName()和ClassLoader.getSystemClassLoader().loadClass()区别

Class.forName()和ClassLoader.getSystemClassLoader().loadClass()区别

时间:2018-07-13 07:42:39

相关推荐

Class.forName()和ClassLoader.getSystemClassLoader().loadClass()区别

转载自Class.forName()和ClassLoader.getSystemClassLoader().loadClass()区别

class A{static {System.out.println("Class A is Loading now");}public A(){System.out.println("A new Class A instance is creating now ...");}};class B{public static void main(String[] argv){try{//Class.forName("A");ClassLoader.getSystemClassLoader().loadClass("A");}catch(Exception e){System.out.println(e);}}};

使用Class.forName()的静态方法jvm会装载类并且执行static {}中的代码,而Class.Loader.loadClass()不会执行static()的代码。

在常用的JDBC驱动中,就是使用了这个方法。

public class Driver extends NonRegisteringDriver implements java.sql.Driver {// ~ Static fields/initializers// ---------------------------------------------//// Register ourselves with the DriverManager//static {try {java.sql.DriverManager.registerDriver(new Driver());} catch (SQLException E) {throw new RuntimeException("Can't register driver!");}}// ~ Constructors// -----------------------------------------------------------/*** Construct a new driver and register it with DriverManager* * @throws SQLException* if a database error occurs.*/public Driver() throws SQLException {// Required for Class.forName().newInstance()}}

以上代码摘录自mysql的jdbc驱动。

Class.forName("com.mysql.jdbc.Driver");Connection conn = DriverManager.getConnection(url,user,pwd);

写程序时候的调用,这也是我当初刚看这段代码的时候,始终想不明白的地方。

现在总算知道了来龙去脉。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。