Sunday, 1 December 2013

What is Class.forName() and Why should we use it?

Class.forName() is a static method of the java.lang.Class that loads a given class into the memory. Didn't understand what is loading of a class into memory? Well let me explain.

Loading of a class into memory is nothing but loading it into RAM, thereby making it accessible to create an object for it and work with it.
When a class is loaded, its static block is executed.

Here is an example on Class.forName()

class ForNameEx
{
    public static void main(String[] args) throws ClassNotFoundException {
        Class.forName("oracle.jdbc.OracleDriver");
        System.out.println("Driver loaded");
    }
}

The above example loads a class called oracle.jdbc.OracleDriver (a class related to JDBC). If you don't have an idea about JDBC, just leave the class name. I just showed it as an example. This method, Class.forName() throws a ClassNotFoundException which clearly means that, it is an exception thrown when the class sent to the Class.forName() is not found. If this happens, then the next statement here isn't executed.

Now, as said earlier, when a class is loaded into the RAM, its static block is executed. Here, the static block in the oracle.jdbc.OracleDriver class is executed. So when we want to execute the static block of a class without creating an object for it, this is a way.

Returns: This method returns the Class object of the given class name.

No comments:

Post a Comment