What is the difference between "Class.forName()" and "Class.forName().newInstance()"?
Maybe an example demonstrating how both methods are used will help you to understand things better. So, consider the following class:
package test;
public class Demo {
public Demo() {
System.out.println("Hi!");
}
public static void main(String[] args) throws Exception {
Class clazz = Class.forName("test.Demo");
Demo demo = (Demo) clazz.newInstance();
}
}
As explained in its javadoc, calling Class.forName(String)
returns the Class
object associated with the class or interface with the given string name i.e. it returns test.Demo.class
which is affected to the clazz
variable of type Class
.
Then, calling clazz.newInstance()
creates a new instance of the class represented by this Class
object. The class is instantiated as if by a new
expression with an empty argument list. In other words, this is here actually equivalent to a new Demo()
and returns a new instance of Demo
.
And running this Demo
class thus prints the following output:
Hi!
The big difference with the traditional new
is that newInstance
allows to instantiate a class that you don't know until runtime, making your code more dynamic.
A typical example is the JDBC API which loads, at runtime, the exact driver required to perform the work. EJBs containers, Servlet containers are other good examples: they use dynamic runtime loading to load and create components they don't know anything before the runtime.
Actually, if you want to go further, have a look at Ted Neward paper Understanding Class.forName() that I was paraphrasing in the paragraph just above.
EDIT (answering a question from the OP posted as comment): The case of JDBC drivers is a bit special. As explained in the DriverManager chapter of Getting Started with the JDBC API:
(...) A
Driver
class is loaded, and therefore automatically registered with theDriverManager
, in one of two ways:
by calling the method
Class.forName
. This explicitly loads the driver class. Since it does not depend on any external setup, this way of loading a driver is the recommended one for using theDriverManager
framework. The following code loads the classacme.db.Driver
:Class.forName("acme.db.Driver");
If
acme.db.Driver
has been written so that loading it causes an instance to be created and also callsDriverManager.registerDriver
with that instance as the parameter (as it should do), then it is in theDriverManager
's list of drivers and available for creating a connection.(...)
In both of these cases, it is the responsibility of the newly-loaded
Driver
class to register itself by callingDriverManager.registerDriver
. As mentioned, this should be done automatically when the class is loaded.
To register themselves during initialization, JDBC driver typically use a static initialization block like this:
package acme.db;
public class Driver {
static {
java.sql.DriverManager.registerDriver(new Driver());
}
...
}
Calling Class.forName("acme.db.Driver")
causes the initialization of the acme.db.Driver
class and thus the execution of the static initialization block. And Class.forName("acme.db.Driver")
will indeed "create" an instance but this is just a consequence of how (good) JDBC Driver are implemented.
As a side note, I'd mention that all this is not required anymore with JDBC 4.0(added as a default package since Java 7) and the new auto-loading feature of JDBC 4.0 drivers. See JDBC 4.0 enhancements in Java SE 6.
Class.forName() gives you the class object, which is useful for reflection. The methods that this object has are defined by Java, not by the programmer writing the class. They are the same for every class. Calling newInstance() on that gives you an instance of that class (i.e. calling Class.forName("ExampleClass").newInstance()
it is equivalent to calling new ExampleClass()
), on which you can call the methods that the class defines, access the visible fields etc.
In JDBC world, the normal practice (according the JDBC API) is that you use Class#forName()
to load a JDBC driver. The JDBC driver should namely register itself in DriverManager
inside a static block:
package com.dbvendor.jdbc;
import java.sql.Driver;
import java.sql.DriverManager;
public class MyDriver implements Driver {
static {
DriverManager.registerDriver(new MyDriver());
}
public MyDriver() {
//
}
}
Invoking Class#forName()
will execute all static initializers. This way the DriverManager
can find the associated driver among the registered drivers by connection URL during getConnection()
which roughly look like follows:
public static Connection getConnection(String url) throws SQLException {
for (Driver driver : registeredDrivers) {
if (driver.acceptsURL(url)) {
return driver.connect(url);
}
}
throw new SQLException("No suitable driver");
}
But there were also buggy JDBC drivers, starting with the org.gjt.mm.mysql.Driver
as well known example, which incorrectly registers itself inside the Constructor instead of a static block:
package com.dbvendor.jdbc;
import java.sql.Driver;
import java.sql.DriverManager;
public class BadDriver implements Driver {
public BadDriver() {
DriverManager.registerDriver(this);
}
}
The only way to get it to work dynamically is to call newInstance()
afterwards! Otherwise you will face at first sight unexplainable "SQLException: no suitable driver". Once again, this is a bug in the JDBC driver, not in your own code. Nowadays, no one JDBC driver should contain this bug. So you can (and should) leave the newInstance()
away.