How to get object of user class using Class.forName in java




Asked on April 03, 2014
Hi All,
I need an example how to get object of  user class using Class.forName in java.

Thanks



Replied on April 03, 2014
To get  object of class which is being passed must be implementing an interface.
Find the sample interface and implementing  class

//interface
package com.concretepage.lang;
public interface ITest {
public void show();
}

//implementing class
package com.concretepage.lang;
public class Test implements ITest {
public void show() {
System.out.println("Hello World!");
}
}


//now main class to get object

package com.concretepage.lang;
public class MainClass {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException{ 
Class<?> c = Class.forName("com.concretepage.lang.Test");
Object ob = c.newInstance();
ITest test = (ITest)ob;
test.show();
}
}

Output

Hello World!

Keep in mind that if we do not have interface for the passing class which is being passed in forName() method then typecasting will throw error.








Replied on April 03, 2014
That is great.  Thanks a lot Arvind

Write Answer











©2024 concretepage.com | Privacy Policy | Contact Us