Is there a way to instantiate a class by name in Java? Is there a way to instantiate a class by name in Java? java java

Is there a way to instantiate a class by name in Java?


Two ways:

Method 1 - only for classes having a no-arg constructor

If your class has a no-arg constructor, you can get a Class object using Class.forName() and use the newInstance() method to create an instance (though beware that this method is often considered evil because it can defeat Java's checked exceptions).

For example:

Class<?> clazz = Class.forName("java.util.Date");Object date = clazz.newInstance();

Method 2

An alternative safer approach which also works if the class doesn't have any no-arg constructors is to query your class object to get its Constructor object and call a newInstance() method on this object:

Class<?> clazz = Class.forName("com.foo.MyClass");Constructor<?> constructor = clazz.getConstructor(String.class, Integer.class);Object instance = constructor.newInstance("stringparam", 42);

Both methods are known as reflection. You will typically have to catch the various exceptions which can occur, including things like:

  • the JVM can't find or can't load your class
  • the class you're trying to instantiate doesn't have the right sort of constructors
  • the constructor itself threw an exception
  • the constructor you're trying to invoke isn't public
  • a security manager has been installed and is preventing reflection from occurring


MyClass myInstance = (MyClass) Class.forName("MyClass").newInstance();


To make it easier to get the fully qualified name of a class in order to create an instance using Class.forName(...), one could use the Class.getName() method. Something like:

class ObjectMaker {    // Constructor, fields, initialization, etc...    public Object makeObject(Class<?> clazz) {        Object o = null;        try {            o = Class.forName(clazz.getName()).newInstance();        } catch (ClassNotFoundException e) {            // There may be other exceptions to throw here,             // but I'm writing this from memory.            e.printStackTrace();        }        return o;    }}

Then you can cast the object you get back to whatever class you pass to makeObject(...):

Data d = (Data) objectMaker.makeObject(Data.class);