2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

Creating an instance using the class name and calling constructor

I have some requirement to create a instance of a dynamic class(At run time).

Means is there any such ways to create an instance of a particular class by passing the class name dynamically and pass parameters to its constructor too.

userimage

You can do it the following way

Class<?> clazz = Class.forName(className);

Constructor<?> constructor= clazz.getConstructor(String.class);

Object obj = constructor.newInstance(new Object[] { constructorArgument });


This will only work for a single string parameter, but you can modify it easily.

Note that the class name has to be a fully-qualified one, i.e. including the namespace. For nested classes, you need to use a dollar (as that's what the compiler uses). For example:


package kodetalk;

public class Clazz

{

    public static class Nested {}

}

To obtain the Class object for that, you'd need Class.forName("kodetalk.Clazz$Nested").


Answer is