Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, connecting to mysql, what is the meaning of Class.forName?

Tags:

java

mysql

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 ();
like image 352
Itay Moav -Malimovka Avatar asked Jul 15 '10 01:07

Itay Moav -Malimovka


2 Answers

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)

like image 56
bwawok Avatar answered Sep 22 '22 14:09

bwawok


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.

like image 34
emory Avatar answered Sep 19 '22 14:09

emory