Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (2.6k points)

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.

1 Answer

0 votes
by (46k points)

Yes, try this:

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

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

Object object = ctor.newInstance(new Object[] { ctorArgument });

That will simply run for a single string parameter of course, but you can adjust it pretty simply.

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

package foo;

public class Outer

{

    public static class Nested {}

}

To concern the Class object for that, you'd 

need Class.forName("foo.Outer$Nested").

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...