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

143,442

Solution 1

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

Solution 2

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

Solution 3

Using newInstance() directly is deprecated as of Java 8. You need to use Class.getDeclaredConstructor(...).newInstance(...) with the corresponding exceptions.

Solution 4

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);

Solution 5

use Class.forName("String name of class").newInstance();

Class.forName("A").newInstance();

This will cause class named A initialized.

Share:
143,442
ict1991
Author by

ict1991

Updated on September 19, 2020

Comments

  • ict1991
    ict1991 over 3 years

    I was looking as the question : Instantiate a class from its string name which describes how to instantiate a class when having its name. Is there a way to do it in Java? I will have the package name and class name and I need to be able to create an object having that particular name.

    • Andreas Dolk
      Andreas Dolk about 12 years
      We instantiate a class and the result is an object (or: instance).
    • c1moore
      c1moore over 7 years
      The answer is yes, but I think you should ask if its a good idea. With great power (reflection) comes great responsibility and you should only use it if you understand and have considered the consequences.
  • Dawood ibn Kareem
    Dawood ibn Kareem about 12 years
    It's worth mentioning that this doesn't work if the class has no parameterless constructor (and has other constructors), or if the parameterless constructor is inaccessible.
  • RamValli
    RamValli over 8 years
    @Simon can you elaborate/give pointer about the security manager?
  • user276648
    user276648 over 7 years
    Can't you simply clazz.newInstance() instead of the getName then fromName?