Friday 12 December 2014

What does Class.forName do exactly?


Class.forName method is used to load a class dynamically.

Example
Class.forName(“Abc”);

Above statement loads class “Abc”, if it is not loaded already, and returns the Class object associated with this class/interface.

Let’s see it by an example

public class Person {
    private int id;
    private String firstName;
    private String lastName;

    static int totalEmployees;

    static{
        System.out.println("Static block is initializing");
    }

    static{
        totalEmployees = 1;
        System.out.println("Total employees set to 1");
    }
    
    public String getFirstName() {
        return firstName;
    }

    public int getId() {
        return id;
    }

    public String getLastName() {
        return lastName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

}

public class PersonTest {
    public static void main(String args[]){
        try {
            Class.forName("Person");
            Class.forName("Person");
        }
        catch (ClassNotFoundException ex) {

        }
    }
}


Output
Static block is initializing
Total employees set to 1


When you call “Class.forName("Person");” first time, then the class Person is dynamically loaded and initialized by the class loader.  Initialization means all static fields are set to default values, static blocks are executed in the order you specified in the class file.

So when I tries to call “Class.forName("Person");” second time, no initialization happens, since class is loaded already (No static blocks executed again).

As I said, class.forName method returns Class object associated with this class. Once you got the Class instance associated with any class, you can initialize the object, by using “newInstance” method of class “Class” like below.

Class c1 = Class.forName("Person");
Person p1 = (Person)c1.newInstance();

public class PersonTest {
    public static void main(String args[]){
        try {
            Class c1 = Class.forName("Person");
            Person p1 = (Person)c1.newInstance();

            p1.setFirstName("Hari");
            p1.setLastName("Krishna");
            p1.setId(358);

            System.out.println(p1.getId() +"." +p1.getFirstName() +" " + p1.getLastName());

        }
        catch (ClassNotFoundException e) {

        }
        catch(InstantiationException e){
            
        }
        catch(IllegalAccessException e){

        }
    }
}


Output
Static block is initializing
Total employees set to 1
358.Hari Krishna




No comments:

Post a Comment