The Class.forName () method is often used in Java development, especially in database development.
By querying the Java documentation we will find that the purpose of using the Class.forName () static method is to dynamically load the class.
Normally during the encoding process, the newinstance () static method under class is typically called to instantiate an object for operation after the load is complete. Therefore, it is useless to use only class.forname () to dynamically load a class, and its ultimate purpose is to instantiate the object.
Experience with database development friends will find out why we did not call the Newinstance () method when we loaded the database driver package.
That is, the JDBC Connection database is written in Class.forName (xxx.xx.xx), and some: Class.forName (xxx.xx.xx). newinstance (), why do you have these two kinds of writing?
As mentioned earlier, Class.forName ("") is the function of requiring the JVM to find and load the specified class, first of all understand that any class in Java will be loaded on the virtual machine to run, and the static code is bound to class, The success of class loading indicates that you have executed your static code and will not go through this static code again.
As we have said earlier, the role of Class.forName (XXX.XX.XX) is to require the JVM to find and load the specified class, and if there is a static initializer in the class, the JVM will necessarily execute the static code snippet of that class.
In the JDBC specification, it is explicitly required that the driver class must register itself with DriverManager, that is, the code of any JDBC driver driver class must resemble the following:
Public class Implements Driver {static {drivermanager.registerdriver (new myjdbcdriver ());}}
Now that we have registered in the static initializer, we only need Class.forName (XXX.XXX) when using JDBC.
Why is Class.forName () useful when loading a database driver package, but not newinstance ()?