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

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!


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);


Class.forName("className").newInstance() always invokes no argument default constructor.

To invoke parametrized constructor instead of zero argument no-arg constructor,

  1. You have to get Constructor with parameter types by passing types in Class[]for getDeclaredConstructor method of Class
  2. You have to create constructor instance by passing values in Object[] for
    newInstance method of Constructor

Example code:

import java.lang.reflect.*;class NewInstanceWithReflection{    public NewInstanceWithReflection(){        System.out.println("Default constructor");    }    public NewInstanceWithReflection( String a){        System.out.println("Constructor :String => "+a);    }    public static void main(String args[]) throws Exception {        NewInstanceWithReflection object = (NewInstanceWithReflection)Class.forName("NewInstanceWithReflection").newInstance();        Constructor constructor = NewInstanceWithReflection.class.getDeclaredConstructor( new Class[] {String.class});        NewInstanceWithReflection object1 = (NewInstanceWithReflection)constructor.newInstance(new Object[]{"StackOverFlow"});    }}

output:

java NewInstanceWithReflectionDefault constructorConstructor :String => StackOverFlow