Skip to main content

What does Class.forname method do?

--
A call to Class.forName("X") causes the class named X to be dynamically loaded (at runtime). A call to forName("X") causes the class named X to be initialized (i.e., JVM executes all its static block after class loading). Class.forName("X") returns the Class object associated with the "X" class. The returned Class
object is not an instance of the "x" class itself.

Class.forName("X") loads the class if it not already loaded. The JVM keeps track of all the classes that have been previously loaded. This method uses the classloader of the class that invokes it. The "X" is the fully qualified name of the desired class.

For example,
package com.abcd;
class AClass { 
    static { 
        System.out.println("static block in AClass");
    }
}

public class Program { 
    public static void main(String[] args) {
        try { 
            Class c   = Class.forName("com.abcd.AClass"); 
        } catch (ClassNotFoundException e) {
        }
        
    }
}
The output is
static block in AClass

Here is one example that uses returned Class to create an instance of AClass:
package com.abcd;
class AClass {
  public AClass() {
    System.out.println("AClass's Constructor");
  }
  static { 
    System.out.println("static block in AClass");
  }
}

public class Program { 
  public static void main(String[] args) {
    try { 
      System.out.println("The first time calls forName:");
      Class c   = Class.forName("com.abcd.AClass"); 
      AClass a = (AClass)c.newInstance();

      System.out.println("The second time calls forName:");
      Class c1 = Class.forName("com.abcd.AClass");

    } catch (ClassNotFoundException e) {
            ...
    } catch (InstantiationException e) {
            ...
    } catch (IllegalAccessException e) {
            ...
    }
        
  }
}
The output is
The first time calls forName:
static block in AClass
AClass's Constructor
The second time calls forName:  
//Calss has been loaded so there is not "static block in AClass" printing out

JDBC Driver Is a Good Example

You may have experience working with JDBC Drivers. For example, the classloader attempts to load and link the Driver class in the "org.gjt.mm.mysql" package. If successful, the static initializer is called.
Class.forName("org.gjt.mm.mysql.Driver");
Connection con = DriverManager.getConnection(url,?myLogin", "myPassword");

Let's see why you need Class.forName() to load a driver into memory. All JDBC Drivers have a static block that registers itself with DriverManager and DriverManager has static an initializer only.
The MySQL JDBC Driver has a static initializer looks like this:
static {
    try {
        java.sql.DriverManager.registerDriver(new Driver());
    } catch (SQLException E) {
        throw new RuntimeException("Can't register driver!");
    }
}

JVM executes the static block and the Driver registers itself with the DriverManager.
You need a database connection to manipulate the database. In order to create the connection to the database, the DriverManager class has to know which database driver you want to use. It does that by iterating over the array (internally a Vector) of drivers that have registered with it and calls the acceptsURL(url) method on each driver in the array, effectively asking the driver to tell it whether or not it can handle the JDBC URL.

Comments

Popular posts from this blog

Asynchronous Vs. Synchronous Communications

Synchronous (One thread):   1 thread -> |<---A---->||<----B---------->||<------C----->| Synchronous (multi-threaded):   thread A -> |<---A---->| \ thread B ------------> ->|<----B---------->| \ thread C ----------------------------------> ->|<------C----->|

WebSphere MQ Interview Questions

What is MQ and what does it do? Ans. MQ stands for MESSAGE QUEUEING. WebSphere MQ allows application programs to use message queuing to participate in message-driven processing. Application programs can communicate across different platforms by using the appropriate message queuing software products. What is Message driven process? Ans . When messages arrive on a queue, they can automatically start an application using triggering. If necessary, the applications can be stopped when the message (or messages) have been processed. What are advantages of the MQ? Ans. 1. Integration. 2. Asynchrony 3. Assured Delivery 4. Scalability. How does it support the Integration? Ans. Because the MQ is independent of the Operating System you use i.e. it may be Windows, Solaris,AIX.It is independent of the protocol (i.e. TCP/IP, LU6.2, SNA, NetBIOS, UDP).It is not required that both the sender and receiver should be running on the same platform What is Asynchrony? Ans. With messag

Advantages & Disadvantages of Synchronous / Asynchronous Communications?

  Asynchronous Communication Advantages: Requests need not be targeted to specific server. Service need not be available when request is made. No blocking, so resources could be freed.  Could use connectionless protocol Disadvantages: Response times are unpredictable. Error handling usually more complex.  Usually requires connection-oriented protocol.  Harder to design apps Synchronous Communication Advantages: Easy to program Outcome is known immediately  Error recovery easier (usually)  Better real-time response (usually) Disadvantages: Service must be up and ready. Requestor blocks, held resources are “tied up”.  Usually requires connection-oriented protocol