Create object using newInstance

In Java we can create object using newInstance() method, it is implemented in the Class class. Class loaded into memory when we execute user defined class before it(User defined class) loads into memory. The Class holds the information of user defined class.

Example:

package com.gudla.newinstance;

public class NewInstance {
    public int i = 10;
    public void testMethod(){
        System.out.println("testMethod is called");
    }
}
package com.gudla.newinstance;

public class NewInstanceTest {
    public static void main(String ags[]) throws ClassNotFoundException, InstantiationException, IllegalAccessException{
        System.out.println(Class.forName("com.gudla.newinstance.NewInstance").newInstance());
        NewInstance obj =(NewInstance)Class.forName("com.gudla.newinstance.NewInstance").newInstance();
        obj.testMethod();
    }
}

Output:

com.gudla.newinstance.NewInstance@15db9742
testMethod is called

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s