I am trying to create a class object dynamically by sending the class name as a string. I searched in all java forums, but I could not get the answer I wanted. Here is my requirement, I have a class called Agent,
package somePack; public class Agent{ private String Id; Private String Name; public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } } package somePack; public class Employee{ private String Id; Private String Name; public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } } public class create{ public static void main(String[] args){ newCreate("Employee"); newCreate("Agent"); } public static void newCreate(String name){ String path="somePack."+name; Class cls=Class.forName(path); System.out.println("Class Name " + cls.getName()); } }
Now my question is: cls.getName () gives me the class name, but now I want to create an object for this class, i.e. for the Employee class and Agent class, respectively, but how can I create an object for them? The string that is being passed may be something else from another method, how can I create an object for such things.
Can someone help me ....
Thanks in advance,
Praveen
source share