JDBC驱动加载理解反射

反射:              Class.forName("com.mysql.jdbc.Driver")

new方法:        Driver driver = new Driver();//com.mysql.jdbc.Driver 

                          DriverManager.registerDriver(driver);

查看Driver源码

public class Driver extends NonRegisteringDriver implements java.sql.Driver {
    //
    // Register ourselves with the DriverManager
    //
    static {
        try {
            java.sql.DriverManager.registerDriver(new Driver());
        } catch (SQLException E) {
            throw new RuntimeException("Can't register driver!");
        }
    }

    /**
     * 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()
    }
  ok,就是说其实起作用的是这一句代码:

 java.sql.DriverManager.registerDriver(new Driver());


第2种方式 Driver driver = new Driver()  其在内部也执行静态代码块,这相当于实例化了两个Driver对象;

第2种方式 Driver driver = new Driver() 会产生对某一种数据库的依赖(会import驱动包),当脱离masql的jar的时程序将无法编译,耦合性较高。

反射:

反射可避免对某一类产生依赖,使耦合性降低

猜你喜欢

转载自www.cnblogs.com/-answer/p/12412039.html
今日推荐