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;
}
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. Commented Sep 18, 2012 at 22:35

1 Answer 1

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();
}   
Sign up to request clarification or add additional context in comments.

Comments