Click to See Complete Forum and Search --> : Instantiation of Objects at run Time.


Sumit Garg
August 23rd, 1999, 04:28 AM
Hello,
I am having a problem that I cant instantiate an object by the normal method of new [Classname](),
instead I have a variable which contains the name of the class whose object is to be instanttiated.
This is for sure that the Class whose object is to be fired will be present in the library.
To make my thing clear: e.g: consider the code

String var = new String("");
var = GetClassName();
// Now I cant say something like Object Obj = new var; where var has the name of the class whose object I can instatiate. I want to just fire that Obect's method after that.
Can U please make it as fast as possible because I know the solution is there but I am unable to implement anything on this.
Thanks a million
sumit

unicman
August 23rd, 1999, 08:09 AM
I think u can load any class at Runtime using 'ClassLoader' class. U can retrieve ClassLoader instance from 'obj.getClass().getClassLoader()'.

Then u can try getting instance of the class u want to instantiate using 'findClass' or 'loadClass' methods.

- UnicMan

August 24th, 1999, 09:28 AM
Here is it

Use java.lang.Class - first use the string var that contains the class name with forName() ie Class myclass = Class.forName(className);(className is a String that contains the class name - case matching must).Then u should have a no arg constructor in ur class.Call myclass.instance() which will create a instance of ur class.Then us the object invoke ur methods.In case u dont have a no arg consturctor then u should use method of java.lang.Class that returns all ctors of ur class and use a suitable ctor to create the object
Hope this is clear