Create new object from a string in Java

This is what you want to do:

String className = "Class1";
Object xyz = Class.forName(className).newInstance();

Note that the newInstance method does not allow a parametrized constructor to be used. (See Class.newInstance documentation)

If you do need to use a parametrized constructor, this is what you need to do:

import java.lang.reflect.*;

Param1Type param1;
Param2Type param2;
String className = "Class1";
Class cl = Class.forName(className);
Constructor con = cl.getConstructor(Param1Type.class, Param2Type.class);
Object xyz = con.newInstance(param1, param2);

See Constructor.newInstance documentation

Leave a Comment