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

Creating an instance using the class name and calling constructor


Yes, something like:

Class<?> clazz = Class.forName(className);Constructor<?> ctor = clazz.getConstructor(String.class);Object object = ctor.newInstance(new Object[] { ctorArgument });

That will only work for a single string parameter of course, but you can modify it pretty 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 foo;public class Outer{    public static class Nested {}}

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


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


You can use reflections

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