[java] Creating an instance using the class name and calling constructor

Is there a way to create an instance of a particular class given the class name (dynamic) and pass parameters to its constructor.

Something like:

Object object = createInstance("mypackage.MyClass","MyAttributeValue");

Where "MyAttributeValue" is an argument to the constructor of MyClass.

This question is related to java reflection instantiation

The answer is


Very Simple way to create an object in Java using Class<?> with constructor argument(s) passing:

Case 1:- Here, is a small code in this Main class:

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Main {

    public static void main(String args[]) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

        // Get class name as string.
        String myClassName = Base.class.getName();
        // Create class of type Base.
        Class<?> myClass = Class.forName(myClassName);
        // Create constructor call with argument types.
        Constructor<?> ctr = myClass.getConstructor(String.class);
        // Finally create object of type Base and pass data to constructor.
        String arg1 = "My User Data";
        Object object = ctr.newInstance(new Object[] { arg1 });
        // Type-cast and access the data from class Base.
        Base base = (Base)object;
        System.out.println(base.data);
    }

}

And, here is the Base class structure:

public class Base {

    public String data = null;

    public Base() 
    {
        data = "default";
        System.out.println("Base()");
    }

    public Base(String arg1) {
        data = arg1;
        System.out.println("Base("+arg1+")");
    }

}

Case 2:- You, can code similarly for constructor with multiple argument and copy constructor. For example, passing 3 arguments as parameter to the Base constructor will need the constructor to be created in class and a code change in above as:

Constructor<?> ctr = myClass.getConstructor(String.class, String.class, String.class);
Object object = ctr.newInstance(new Object[] { "Arg1", "Arg2", "Arg3" }); 

And here the Base class should somehow look like:

public class Base {

    public Base(String a, String b, String c){
        // This constructor need to be created in this case.
    }   
}

Note:- Don't forget to handle the various exceptions which need to be handled in the code.


If class has only one empty constructor (like Activity or Fragment etc, android classes):

Class<?> myClass = Class.forName("com.example.MyClass");    
Constructor<?> constructor = myClass.getConstructors()[0];


Another helpful answer. How do I use getConstructor(params).newInstance(args)?

return Class.forName(**complete classname**)
    .getConstructor(**here pass parameters passed in constructor**)
    .newInstance(**here pass arguments**);

In my case, my class's constructor takes Webdriver as parameter, so used below code:

return Class.forName("com.page.BillablePage")
    .getConstructor(WebDriver.class)
    .newInstance(this.driver);

You can use Class.forName() to get a Class object of the desired class.

Then use getConstructor() to find the desired Constructor object.

Finally, call newInstance() on that object to get your new instance.

Class<?> c = Class.forName("mypackage.MyClass");
Constructor<?> cons = c.getConstructor(String.class);
Object object = cons.newInstance("MyAttributeValue");

when using (i.e.) getConstructor(String.lang) the constructor has to be declared public. Otherwise a NoSuchMethodException is thrown.

if you want to access a non-public constructor you have to use instead (i.e.) getDeclaredConstructor(String.lang).


If anyone is looking for a way to create an instance of a class despite the class following the Singleton Pattern, here is a way to do it.

// Get Class instance
Class<?> clazz = Class.forName("myPackage.MyClass");

// Get the private constructor.
Constructor<?> cons = clazz.getDeclaredConstructor();

// Since it is private, make it accessible.
cons.setAccessible(true);

// Create new object. 
Object obj = cons.newInstance();

This only works for classes that implement singleton pattern using a private constructor.


You can also invoke methods inside the created object.

You can create object instant by invoking the first constractor and then invoke the first method in the created object.

    Class<?> c = Class.forName("mypackage.MyClass");
    Constructor<?> ctor = c.getConstructors()[0];
    Object object=ctor.newInstance(new Object[]{"ContstractorArgs"});
    c.getDeclaredMethods()[0].invoke(object,Object... MethodArgs);

You can use reflections

return Class.forName(className).getConstructor(String.class).newInstance(arg);

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to reflection

Get properties of a class Get class name of object as string in Swift Set field value with reflection Using isKindOfClass with Swift I want to get the type of a variable at runtime Loading DLLs at runtime in C# How to have Java method return generic list of any type? Java reflection: how to get field value from an object, not knowing its class Dynamically Add C# Properties at Runtime Check if a property exists in a class

Examples related to instantiation

Instance member cannot be used on type How do I write a custom init for a UIView subclass in Swift? Is there a way to instantiate a class by name in Java? Why do I get an error instantiating an interface? Creating an instance using the class name and calling constructor What is the difference between "Class.forName()" and "Class.forName().newInstance()"? How to create a generic array in Java? C++ Object Instantiation Create an instance of a class from a string