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.
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:
WeJustWantToLoadTheDriverToJVMOnly,ButNotNeedToUserTheInstanceOfDriver,SoCallClass. forname (XXX. xx. xx)IsEnough,IfYouCallClass. forname (XXX. xx. xx). newinstance (),TheResultWillSameAsCallingClass. forname (XXX. xx. xx ),BecauseClass. forname (XXX. xx. xx). newinstance ()WillLoadDriverFirst,AndThenCreateInstance,ButTheInstacneYouWillNeverUseInUsual,SoYouNeedNotToCreateIt.Summary: the final purpose of the JDBC database driver is to allow programmers to get database connections and perform JDBC-compliant database operations. The process of getting the connection does not require you to instantiate the driver by yourself, but through drivermanger. getconnection (string
Str );. Therefore, programmers generally do not instantiate a database driver to use the methods unless they have special requirements.
Most Reprinted from: http://hi.baidu.com/zxf1986518/blog/item/c5fac9cebbc33b32b600c849.html