For most people, the first time they seeclass.forName(String className)this code should be when usingJDBCthe method to connect to the database.
Example
Class.forNameAfter passing in com.mysql.jdbc.Driver, you know that the database I am connecting to is MySQL. Why is this? Let's look at the source code:
We find that it calls the forName0 method. Let's continue tracing and take another look:
It is a native method, so the source code ends here. Let's take a look at the description in the official documentation:https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#forName(java.lang.String)
Returns the Class object associated with the class or interface with the given string name, using the given class loader. Given the fully qualified name for a class or interface (in the same format returned by getName) this method attempts to locate, load, and link the class or interface. The specified class loader is used to load the class or interface. If the parameter loader is null, the class is loaded through the bootstrap class loader. The class is initialized only if the initialize parameter is true and if it has not been initialized earlier.
A rough translation is: Returns a Class object for a given class or interface. If no classloader is given, the root class loader will be used. If the initialize parameter is passed as true, then the given class will be initialized if it has not been initialized before. In the first step of JDBC, the parameter we pass in is com.mysql.jdbc.Driver. That is to say, this class will be initialized. Let's look at the contents of this class:
We find that this class is also super simple. It has a constructor and a static code block. We know that when a class is initialized, the contents of the static code block will be executed. That is to say, weClass.forNameand directly writingDriverManager.registerDriver(new Driver)The two are functionally equivalent. Let's switch to this style and try again:
We find that the code still executes normally.
Let's summarize: Class.forNameThe purpose of the method is to initialize the given class. And in the MySQL Driver class we provided, it registers the driver in the static code block through JDBC's DriverManager. We can also directly use JDBC's driver manager to register the MySQL driver, thereby replacing the use ofClass.forName。
Original URL: http://linuxsogood.org/1580.html