Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between using .newInstance() and not using?

Tags:

java

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");
...
like image 851
Bala Avatar asked Aug 22 '14 09:08

Bala


1 Answers

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)
like image 196
Jon Skeet Avatar answered Oct 03 '22 02:10

Jon Skeet