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

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!

Leave a Comment