5

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");
...
1
  • Just use last option. You don't need to create any instance of the driver. Just needed to load the driver class. Commented Aug 22, 2014 at 9:30

3 Answers 3

7

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Now it looks great, +1 for the detailed answer :)
0
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.

Comments

0
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.