TheLameProgrammer TheLameProgrammer - 2 years ago 74
Java Question

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

is an argument to the constructor of

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download