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.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:
Class<?> cl = Class.forName("javax.swing.JLabel"); Constructor<?> cons = cl.getConstructor(String.class);
The call to getConstructor
specifies that you want the constructor that takes a single String
parameter. Now to create an instance:
Object o = cons.newInstance("JLabel");
And you're done.
P.S. Only use reflection as a last resort!
The following will work for you. Try this,
Class[] type = { String.class }; Class classDefinition = Class.forName("javax.swing.JLabel"); Constructor cons = classDefinition .getConstructor(type); Object[] obj = { "JLabel"}; return cons.newInstance(obj);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With