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 came across this helpful link with code which works perfectly when updated to hit against my web server. I can do absolutely everything.

Now, the only thing I do not fully understand is the Class.forName().

Why is this being used? Can this be done differently? Is this a work around for something else? Adding a reference? Creating a class as implementing/extending another one?

I want to fully understand what is going on, but this is in my way.

Thank you

See Question&Answers more detail:os

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

1 Answer

That code is forcing the class representing the MySQL driver to load and initialize. In Java, a class is not loaded unless it is necessary that the class gets loaded. Since JDBC code usually never directly references the driver, it wouldn't get loaded without Class.forName (or some other equivalent alternatives).

Note that it is necessary to both load and initialize the class, which are 2 different things.

Also, note that it is not necessary to call .newInstance() -- the static initializer of the Driver already registers itself as a JDBC driver.

Finally, note that with the Service Loader API it is usually not necessary to call Class.forName() to load the driver: it can be loaded automatically.


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

548k questions

547k answers

4 comments

86.3k users

...