Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate a class object with constructor that accepts a string parameter?

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?

like image 267
HAMID Avatar asked Aug 26 '10 10:08

HAMID


2 Answers

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!

like image 51
mwittrock Avatar answered Sep 18 '22 17:09

mwittrock


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); 
like image 35
Jothi Avatar answered Sep 18 '22 17:09

Jothi