1

Possible Duplicate:
Creating an instance using the class name and calling constructor

How can I create an object based on the content of a string passed to a method? For example

createObj(String nameclass){
 **class passed** obj;
}
Community
  • 1
  • 1
  • Nearly a duplicate, but the answers in the other article are unnecessarily complicated for the no-args constructor case, where `clazz.newInstance()` is all that is needed. – DNA Sep 18 '12 at 22:35

1 Answers1

6

You can use Class.newInstance() to construct an instance of the class. You will, however, need to obtain the Class<> object using Class.forName(...)

<T> T createObj(String nameclass) throws ClassNotFoundException,
        InstantiationException, IllegalAccessException {

    Class<T> clazz = (Class<T>) Class.forName(nameclass);

    // assumes the target class has a no-args Constructor
    return clazz.newInstance();
}   
munyengm
  • 15,029
  • 4
  • 24
  • 34