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

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

java - Better understaning - Class.forName("com.mysql.jdbc.Driver").newInstance ();

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...