What is the purpose of this line?
It does not return a value or set the state of an existing class/object (or is it?)
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
It uses reflection to look on the classpath for a class called "com.mysql.jdbc.Driver" and makes a new instance of it.
In your code when you write
Integer foo = new Integer()
You could instead write
Integer foo = Class.forName("java.lang.Integer").newInstance()
But why go to all this trouble? Because you want to load your database driver at runtime, not hard code it in. So if you change databases, you just changes a config file that would load a different database driver. In your specific case it may not matter, but it does open up new possibilities on database configuration (and this Class.forName jazz is how it is usually done)
Almost certainly, com.mysql.jdbc.Driver has a static initializer that looks like this:
static {java.sql.DriverManager.registerDriver(new com.mysql.jdbc.Driver())};
This static initializer is called when you use the forName method. So without realizing it you registered the MySQL driver.
As for the newInstance, I don't know why it is there. It seems unnecessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With