Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an object dynamically where the class name is given as a string

Tags:

java

I'm trying to create an object of a class dynamically by sending the class name as a string. I have searched in all the java forums but i couldn't get the answer which i wanted. Here is my requirement, i have a class with name 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 the object for that class i.e., for Employee class and Agent class respectively, but how can i create the object for them? The string that is passed may be something else from the other method, how can i create an object for such kind of things.

Can anyone help me....

Thank you in advance,

like image 674
Praveen Avatar asked Oct 10 '12 05:10

Praveen


Video Answer


1 Answers

but now i want to create the object for that class

Then use the Class.newInstance() method if you never need to handle constructors with arguments, or use Class.getConstructor(...) or Class.getConstructors() otherwise. (Call Constructor.newInstance() to invoke the constructor.)

like image 136
Jon Skeet Avatar answered Sep 25 '22 12:09

Jon Skeet