Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Where "MyAttributeValue" is an argument to the constructor of MyClass.

like image 784
TheLameProgrammer Avatar asked May 23 '11 08:05

TheLameProgrammer


People also ask

Can you create an instance of a class using its constructor?

When you create an object, you are creating an instance of a class, therefore "instantiating" a class. The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate. The constructor initializes the new object.

How do you create an instance of a reflection in Java?

We can use newInstance() method on the constructor object to instantiate a new instance of the class. Since we use reflection when we don't have the classes information at compile time, we can assign it to Object and then further use reflection to access it's fields and invoke it's methods.


1 Answers

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

like image 182
Jon Skeet Avatar answered Sep 30 '22 18:09

Jon Skeet