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?
Class.newInstanceinvokes 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
Constructorinstance like this:The call to
getConstructorspecifies that you want the constructor that takes a singleStringparameter. Now to create an instance:And you’re done.
P.S. Only use reflection as a last resort!