JDBC driver loading appreciated reflection

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

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

                          DriverManager.registerDriver(driver);

View Source 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
     A Database error Occurs IF *. 
     * / 
    Public Driver () throws SQLException {
         // the Required for the Class.forName () the newInstance (). 
    } 
  OK, that is to say it is in fact a function of the code: 

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

 



A second type Driver driver = new Driver () which also perform a static block inside, which is equivalent to two examples of the objects Driver;

A second type Driver driver = new Driver () will produce a certain kind of dependency database (driver package will import), when the process from the jar masql will not compile high coupling.

 

reflection:

Reflection can be avoided to some kind of dependence, decrease the coupling

Guess you like

Origin www.cnblogs.com/-answer/p/12412039.html