Creating an object dynamically when the class name is specified as a string

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,

+7
source share
3 answers

but now I want to create an object for this class

Then use the Class.newInstance() method if you do not need to process the constructors with arguments or use Class.getConstructor(...) or Class.getConstructors() otherwise. (Call Constructor.newInstance() to call the constructor.)

+8
source

Use Class # newInstance ()

 Object o = Class.forName(path).newInstance(); 

Then you can pass this to the agent.

 Agent agent = (Agent) Class.forName(path).newInstance(); 
+6
source

Based on the fact that the class has a default constructor (that is, without parameters), you can simply call Class#newInstance .

If it has options, it gets a little harder.

You will need to get a link to the corresponding Constructor via Class#getConstructor , passing the types of the expected parameter types.

After that, you can call Constructor#newInstance , passing it the appropriate objects

+5
source

All Articles