What is the difference between "Class.forName()" and "Class.forName().newInstance()"?

298,493

Solution 1

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 the DriverManager, in one of two ways:

  1. 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 the DriverManager framework. The following code loads the class acme.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 calls DriverManager.registerDriver with that instance as the parameter (as it should do), then it is in the DriverManager's list of drivers and available for creating a connection.

  1. (...)

In both of these cases, it is the responsibility of the newly-loaded Driver class to register itself by calling DriverManager.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.

Solution 2

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.

Solution 3

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.

Solution 4

1 : if you are interested only in the static block of the class , the loading the class only would do , and would execute static blocks then all you need is:

Class.forName("Somthing");

2 : if you are interested in loading the class , execute its static blocks and also want to access its its non static part , then you need an instance and then you need:

Class.forName("Somthing").newInstance();

Solution 5

Class.forName() gets a reference to a Class, Class.forName().newInstance() tries to use the no-arg constructor for the Class to return a new instance.

Share:
298,493

Related videos on Youtube

Johanna
Author by

Johanna

Updated on June 04, 2021

Comments

  • Johanna
    Johanna almost 3 years

    What is the difference between Class.forName() and Class.forName().newInstance()?

    I do not understand the significant difference (I have read something about them!). Could you please help me?

  • Johanna
    Johanna over 14 years
  • Johanna
    Johanna over 14 years
    in the above site is written that:"Calling the Class.forName automatically creates an instance of a driver and registers it with the DriverManager, so you don't need to create an instance of the class. If you were to create your own instance, you would be creating an unnecessary duplicate, but it would do no harm." it means that by Class.forName you will create an instance outomatically and if you want to create the other it will make an unnecessary instance So both Calss.forName() and Class.forName().newInstance() will create an instance of the driver!!
  • Devanshu Mevada
    Devanshu Mevada over 14 years
    JDBC drivers are "special", they are written with a static initialization block where an instance is created and passed as parameter of DriverManager.registerDriver. Calling Class.forName on a JDBC driver causes its initialization and thus the execution of the static block. Have a look at java2s.com/Open-Source/Java-Document/Database-DBMS/… for an example. So this is actually a particular case due to driver internals.
  • Mr. Lance E Sloan
    Mr. Lance E Sloan about 11 years
    I've noticed that in another answer, using Class.newInstance() is strongly discouraged. It's recommended to use Class.getConstructor(), followed by Constructor.newInstance() in turn. It avoids masking possible exceptions.
  • Code Enthusiastic
    Code Enthusiastic almost 11 years
    "newInstance allows to instantiate a class that you don't know until runtime" made my day. Thanks.
  • Chiseled
    Chiseled over 9 years
    +1 for the detailed answer. One point though , With JDBC 4.0 one does not even need to use Class.forName .... Java's Service Provider Mechanism SPM loads the database driver automatically. One only needs to specify the driver jar in the classpath. Refer to this stackoverflow.com/questions/26551648/…
  • Gaurav
    Gaurav over 4 years
    Excellent answer! Clear and concise!