Finally, I understand why only class. forname () is used to load the database driver !! It's been bothering me for 2 hours !! I hope this article will be helpful to you.
The class. forname () method is often used in Java Development, especially in database development. By querying Java documentation, we will find that the purpose of using the class. forname () static method is to dynamically load classes. After loading, you must call the newinstance () static method under the class to instantiate the object for operation. Therefore, it is useless to use class. forname () alone to dynamically load classes. The ultimate goal is to instantiate objects.
It is necessary to mention the difference between newinstance () and new in the class ?, First, newinstance () is a method, while new is a keyword. Second, the use of newinstance () in class is limited, because it generates an object and can only call constructors without parameters, this restriction does not apply to generating objects using the new keyword.
So far, we can summarize the following:
Class. forname ("") returns the class
Class. forname (""). newinstance () returns the object
If you have experience in database development, you may find that when we load the database driver package, some of them did not call the newinstance () method? That is to say, some JDBC statements to connect to the database are class. forname (XXX. XX. XX); but there are some: class. forname (XXX. XX. XX ). newinstance (). Why are these two methods used?
Class. forname (""); is used to require JVM to search for and load the specified class. If there is a static initiator in the class, JVM will certainly execute the static code segment of the class. In the JDBC specification, the driver class must register itself with drivermanager, that is, any JDBC
The driver code must be similar to the following:
Public Class Myjdbcdriver Implements Driver {
Static {
Drivermanager. registerdriver (New Myjdbcdriver ());
}
}
Since the static initialization has been registered, we only need class. forname (XXX. XXX); To use JDBC.
References in English are as follows:
WeJustWantToLoadTheDriverToJVM
Only,ButNotNeedToUserTheInstanceOf
Driver,SoCallClass. forname (XXX. xx. xx)IsEnough,
IfYouCallClass. forname (XXX. xx. xx). newinstance (),The
ResultWillSameAsCallingClass. forname (XXX. xx. xx ),
BecauseClass. forname (XXX. xx. xx). newinstance ()WillLoadDriver
First,AndThenCreateInstance,ButThe
InstacneYouWillNeverUseInUsual,So
YouNeedNotToCreateIt.