I would like to instantiate an object from its Class
object, using the constructor that accepts a single String
argument.
Here is some code that approaches what I want:
Object object = null;
Class classDefinition = Class.forName("javax.swing.JLabel");
object = classDefinition.newInstance();
However, it instantiates the JLabel
object with no text. I would like to use the JLabel
constructor that accepts a string as the initial text. Is there a way to select a specific constructor from a Class
object?
Some times it's not necessary to create object for the class to call is constructors and methods. You can call methods of class without creating direct object. It's very easy to call a constructor with parameter.
the output will be:
Hello, I'm a constructor. Welcome, User
Hello.
Class.forName("RunDemo"); will load the RunDemo Class.
Constructor c=RunDemo.class.getConstructor(String.class); getConstructor() method of Constructor class will return the constructor which having String as Argument and its reference is stored in object 'c' of Constructor class.
RunDemo d=(RunDemo)c.newInstance("User"); the method newInstance() of Constructor class will instantiate the RundDemo class and return the Generic version of object and it is converted into RunDemo type by using Type casting.
The object 'd' of RunDemo holds the reference returned by the newInstance() method.
Class.forName("className").newInstance()
always invokes no argument default constructor.To invoke parametrized constructor instead of zero argument no-arg constructor,
Constructor
with parameter types by passing types inClass[]
forgetDeclaredConstructor
method ofClass
Object[]
fornewInstance
method ofConstructor
Example code:
output:
The following will work for you. Try this,
Class.newInstance
invokes the no-arg constructor (the one that doesn't take any parameters). In order to invoke a different constructor, you need to use the reflection package (java.lang.reflect
).Get a
Constructor
instance like this:The call to
getConstructor
specifies that you want the constructor that takes a singleString
parameter. Now to create an instance:And you're done.
P.S. Only use reflection as a last resort!