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

I see a lot of java examples connecting to db calling newInstance() . Some do not use it at all. I tried both and it works great. I could not understand why some use and some do not?

 ... Class.forName("com.mysql.jdbc.Driver").newInstance(); ... ... Class.forName("com.mysql.jdbc.Driver"); ... 
+5
source share
3 answers

In modern Java, none of them are required.

The reason for using Class.forName in the "good old days" was that it would run type initialization code that would register the driver with JDBC. You do not need to create a new driver instance, although your first example was never required.

However, this is not required these days - DriverManager uses a standard service provider's mechanism to search for drivers. I would be surprised to see product quality drivers that did not support it now.

In other cases, when you can see the code calling Class.forName() with or without newInstance() , these two are separate calls:

  • Class.forName(String) is a static method that finds / loads a Class object with the fully qualified name specified ... just as if you used Foo.class at compile time, but not knowing the name Foo
  • Class.newInstance() is an instance method that creates a new instance of the class represented by the Class object, which is the method object, calling the constructor without parameters. So, Foo.class.newInstance() bit like new Foo() - except that you do not need to know Foo at compile time (for example, if you received a Class link through Class.forName ) or accepted it as a method parameter)
+7
source
 Class.forName("com.mysql.jdbc.Driver"); 

This simply initializes the specified class in the class loader.

 Class.forName("com.mysql.jdbc.Driver").newInstance(); 

Returns an instance of this class.

In this particular case, initializing the Driver class is sufficient.

+1
source
 Class.forName("com.mysql.jdbc.Driver"); 

This will dynamically load the given class name; if else exists, it will throw a ClassNotFoundException .

 Class.forName("com.mysql.jdbc.Driver").newInstance(); 

In addition to this, it will be done above, a new object / instance of the given class name will also be created.

In jdbc, the first is enough, since we only need to register the jdbc driver, there is no need to explicitly create a new object / instance.

You can also manually load jdbc drivers using command line options.

 java -Djdbc.drivers=com.mysql.jdbc.Driver MyApp 
0
source

Source: https://habr.com/ru/post/1200911/


All Articles