Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am told that the prefered method to load the JDBC driver is :

Class.forName(driverName);

I understand that this is better for a dynamic decision between multiple drivers maybe read from an XML config file or user input. The thing I am curious about is how does invoking this statement loads the stated driver into the environment where we are not even storing the resultant "Class" object anywhere. The JavaDocs entry says:

public static Class forName(String className)
                 throws ClassNotFoundExceptionReturns 

returns the Class object associated with the class or interface with the given string name

In that case, how do the Java developers managed to facilitate the existence of driver object with merely this statement?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
141 views
Welcome To Ask or Share your Answers For Others

1 Answer

The Class#forName() runs the static initializers (you know, static applies to the class, not to the instance). The JDBC driver implementation should register itself in the static initializer.

public class SomeDriver implements Driver {

    static {
        DriverManager.registerDriver(new SomeDriver());
    }

}

Note that there exist buggy JDBC drivers such as org.gjt.mm.mysql.Driver which incorrectly registers itself inside the constructor instead. That's why you need a newInstance() call afterwards on such drivers to get them to register themselves.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...