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