Reputation: 11234
I see a lot of java examples connecting to a db, makes a call to newInstance()
. Some don't use it at all. I tried both and are working fine. I couldn't understand why some use and some don't?
...
Class.forName("com.mysql.jdbc.Driver").newInstance();
...
...
Class.forName("com.mysql.jdbc.Driver");
...
Upvotes: 5
Views: 1378
Reputation: 1500145
In modern Java, neither of these is needed.
The reason for using Class.forName
in "the good old days" was that it would run the type initialization code, which would register the driver with JDBC. You don't need to create a new instance of the driver though, so your first example was never required.
However, these days it isn't required - DriverManager
uses the standard service provider mechanism to find drivers. I'd be surprised to see any production-quality drivers that didn't support this now.
In other cases where you might see code calling Class.forName()
with or without newInstance()
, the two are separate calls:
Class.forName(String)
is a static method which finds/loads a Class
object with the specified fully-qualified name... just as if you'd used Foo.class
at compile-time, but without knowing the name Foo
Class.newInstance()
is an instance method which creates a new instance of the class represented by the Class
object which is the target of the method, calling the parameterless constructor. So Foo.class.newInstance()
is a little bit like new Foo()
- except again, you don't need to know Foo
at compile-time (e.g. if you've obtained a Class
reference via Class.forName
, or accepted it as a method parameter)Upvotes: 7
Reputation:
Class.forName("com.mysql.jdbc.Driver");
This will dynamically load the given class name, if exist else will throw ClassNotFoundException
.
Class.forName("com.mysql.jdbc.Driver").newInstance();
This will do the above in addition to that, will also create a new object/instance of the given class name.
In jdbc, the first one is enough, as we only need to register the jdbc driver, there is no need to create new object/instance explicitly.
You can also, load the jdbc drivers manually by command line options.
java -Djdbc.drivers=com.mysql.jdbc.Driver MyApp
Upvotes: 0
Reputation: 121998
Class.forName("com.mysql.jdbc.Driver");
That just initializes the mentioned class in class loader.
Class.forName("com.mysql.jdbc.Driver").newInstance();
Returns the instance of that class.
In this specific case initialization of Driver class is enough.
Upvotes: 0