views:

68

answers:

2

I'm having a problem of instantiating a class object, what I want to do is to instantiate the object with constructor accepting "String",

here is the code:

Object object = null;
Class classDefinition = Class.forName("javax.swing.JLabel");
object = classDefinition.newInstance();

it instantiate the JLabel object without a text, i want it to instantiate the object with a text "JLabel"...

any ideas will be much appreciated?

+1  A: 

The following code will wroks 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);
Jothi
Thanks for your respond
HAMID
+2  A: 

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!

mwittrock
+1 for formatting your answer :-)
Stephen C
Thank you so much that's very helpful
HAMID