Home  >  Forum  >  Core Java
Post New Query

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


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

Thanks
joined on
March 14,2013
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.




joined on
March 27,2014
Replied on April 03,2014

That is great.  Thanks a lot Arvind

Write Answer








Copyright ©2017 concretepage.com, all rights reserved |Privacy Policy | Contact Us